1. 程式人生 > >SSH JavaWeb學生資訊管理系統實現

SSH JavaWeb學生資訊管理系統實現

上週週末斷網。。。。。無聊的時候寫的demo,SSH的。

SIMS(Student Information Management System,學生資訊管理系統) 包括登入、學生資訊錄入,修改,刪除,查詢,資料批量匯出等等功能。

開發環境:Eclipse ,jdk1.6

框架:SpringMvc+Hibernate(ORM工具)

前臺:JSP

資料庫:MySQL

眾所周知,Spring配置是相當頭疼的,後面儘量用Springboot寫一下(當然得先學,省去自己配製還是相當方便的)。本來想把專案原始碼放到Github上面,

但是還要自己配置,就懶得放了。。。

話不多說,先看下目錄結構:


配置檔案有三個,Springmvc.xml,applicationContext.xml,web.xml;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SIMS</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
  <filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>sessionFactoryBeanName</param-name>
      <param-value>sessionFactory</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>org.SIMS.controller.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

跟普通的web.xml一樣,多了一個簡單的過濾器,功能是判斷當前使用者是否登陸過。有的話放行,沒有的話讓其跳轉到登入介面。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:property-placeholder location="/WEB-INF/config/resources.properties" ignore-unresolvable="true"/>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    <!-- 掃描註解Bean -->
    <context:component-scan base-package="org.**.service,org.**.dao">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- apache dbcp連線池配置-->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${connection.driverClassName}"></property>
        <property name="url" value="${connection.url}"/>
        <property name="username" value="${connection.username}"/>
        <property name="password" value="${connection.password}"/>
	</bean>

    <!-- SessionFactory配置 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />	
		<property name="packagesToScan" value="org.**.domain"/>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				
				<!-- 只掃描class檔案,不掃描hbm,預設兩個都搜尋 -->
                <prop key="hibernate.archive.autodetection">class</prop>
                <!-- 不檢查@NamedQuery -->
                <prop key="hibernate.query.startup_check">false</prop>
                
                <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
                <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
				<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
				<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
				<prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>
			</props>
		</property>
		<property name="namingStrategy">
			<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
		</property>
	</bean>
	
	<!-- 事務管理 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 事務註解 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
</beans>

上面這個applicationContext.xml是配置一些bean,主要包括資料庫,事務管理,上傳檔案等等。

SpringMvc的話功能主要是掃描註解,對映處理器,檢視解析器,靜態資源對映等等。

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 開啟controller註解支援 -->
    <context:component-scan base-package="org.**.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- 註冊DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapte -->
	<mvc:annotation-driven />

    <mvc:view-controller path="/" view-name="redirect:/index"/>
    
    <!-- 當在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 對映時,能對映靜態資源 -->
    <mvc:default-servlet-handler/>

    <!-- 靜態資源對映 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>

    <!-- 預設的檢視解析器 在上邊的解析錯誤時使用 (預設使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
</beans>

有了這幾個檔案,就可以完成Mvc的操作了,前臺發起交易,後臺處理完成返回檢視經過檢視解析器處理得到一個JSP頁面。

這個系統有兩種角色,Administrator和Student,由於是簡單的demo,我就沒給註冊介面,手動添加了管理員資訊入庫,然後過濾器實現登入過濾,登入過濾如下:

package org.SIMS.controller;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.SIMS.domain.Administrator;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest req= (HttpServletRequest)request;
		HttpServletResponse res= (HttpServletResponse)response;
		String url = req.getRequestURI();
		HttpSession session = req.getSession();
		Administrator ad = (Administrator) session.getAttribute("Admin");
		System.out.println(session.getAttribute("Admin"));
		if(ad!=null || url.endsWith("login")||url.endsWith(".css")||url.endsWith(".js")||url.endsWith("gakki.png")||url.endsWith("loginfmbg.png")||url.endsWith("SSH_market/")){//第一次登入的話放行,不然跳轉至登陸頁面
		// pass the request along the filter chain
			chain.doFilter(req, res);
		}else{
			//未登入的話就跳轉至登陸頁面
			req.getRequestDispatcher("/login.jsp").forward(req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}


下面以登入為例,請求到後臺,dispatchServlet分發請求,HandlerMapping來處理對映,根據前臺發的交易名字去找註解為"/login/login"的方法,即下面的Controller中的login方法。找到之後進行操作,完成返回檢視,經viewResolver渲染得到JSP檔案來展示。

package org.SIMS.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.SIMS.domain.Administrator;
import org.SIMS.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	private StudentService studentservice;
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response){
		String name = request.getParameter("name");
		String pwd =request.getParameter("pwd");
		Administrator ad = studentservice.getAdmin(name,pwd);
		if(ad==null){
			//失敗的情況,跳轉失敗頁面要麼重新登入
			System.out.println("沒有該使用者!");
		}
		request.getSession().setAttribute("Admin", ad);
		return "redirect:/index.jsp";
	}
}

程式碼就不一一羅列了,相信大家應該會。登陸進去之後,就是普通的CRUD操作了,我不會寫介面,難看了別罵我。。。。

CRUD就是普通的前臺發起交易,後臺Controller-service-dao呼叫完成之後生成檢視用檢視解析器解析之後返回jsp頁面作展示。

下面是登入介面:



登陸進來之後,是首頁:


選中某個記錄進行編輯:


修改完電話號碼身份證號之後更新如圖:


然後是各按條件查詢的功能:


查詢完了結果如下:

資料批量匯出:


其它功能就不一一羅列了。

———————————————————————————————————————

看完《李狗嗨》和《逃避可恥但有用》,簡直太好看了,被gakki萌化了,好看!!!