1. 程式人生 > >如何使用spring-springmvc-jdbc實現使用者登入?

如何使用spring-springmvc-jdbc實現使用者登入?

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>mvc01</display-name>
  <!--直接在位址列輸入 工程名 就可以自動跳轉到下面login頁面  -->
  <welcome-file-list>
  	<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
  </welcome-file-list>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</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>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc-servlet.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
</web-app>

applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
         
         <!-- spring掃描包下面所有的類,對註解的支援 -->
         <context:component-scan base-package="cn.kgc.service"></context:component-scan>
          <context:component-scan base-package="cn.kgc.dao"></context:component-scan>
</beans>

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
		<!-- 對控制器註解進行支援 -->
       <context:component-scan base-package="cn.kgc.controller"></context:component-scan>
       <mvc:annotation-driven></mvc:annotation-driven>
       
       <!-- 靜態資源的檔案 -->
       <mvc:resources location="/statics/" mapping="/statics/**"/>
       
       <!-- 配置檢視解析器 -->
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
               <property name="prefix" value="/WEB-INF/jsp/"></property>
               <property name="suffix" value=".jsp"></property>
            </bean>
</beans>

UserController.java

package cn.kgc.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import cn.kgc.pojo.User;
import cn.kgc.service.UserService;
import cn.kgc.tools.Constans;


@Controller
@RequestMapping("/user")
public class UserController{
      private Logger logger=Logger.getLogger(UserController.class);
      
      @Resource
      private UserService userService;
      
      @RequestMapping(value="/login.html")
      public String login(){
      return "login";
      }
      
      @RequestMapping(value="/dologin.html",method=RequestMethod.POST)
      public String doLogin(@RequestParam String userCode,@RequestParam String userPassword,HttpServletRequest request,HttpSession session){
              User user=userService.login(userCode,userPassword);
              System.out.println(user);
              if(user!=null){
              session.setAttribute(Constans.USER_SESSION, user);
            /*  return "redirect:/user/main.html";*/
              return "frame";
                //response.sendRedirect("jsp/aa.jsp")
              }else{
              request.setAttribute("error", "使用者名稱和密碼錯誤");
              return "login";
              }
      }
      
      @RequestMapping(value="/main.html")
      public String main(){
      
          return "frame";      
      }
      
      @RequestMapping(value="/exist.html")
      public String exist(HttpSession session){
      session.invalidate();
return "redirect:/user/exist1.html";
      
      }
      
      @RequestMapping("exist1.html")
      public String exist1(){
      return "login";
      }
}

BaseDao.java

package cn.kgc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.kgc.tools.ConfigManager;

/**
 * 操作資料庫的基類--靜態類
 * @author Administrator
 *
 */
public class BaseDao {	
	
	/**
	 * 獲取資料庫連線
	 * @return
	 */
	public static Connection getConnection(){
		Connection connection = null;
		String driver = ConfigManager.getInstance().getValue("driver");
		String url = ConfigManager.getInstance().getValue("url");
		String user = ConfigManager.getInstance().getValue("user");
		String password = ConfigManager.getInstance().getValue("password");
		try {
			//載入驅動
			Class.forName(driver);
			//獲得連線物件
			connection = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}
	/**
	 * 查詢操作
	 * @param connection
	 * @param pstm
	 * @param rs
	 * @param sql
	 * @param params
	 * @return
	 */
	public static ResultSet execute(Connection connection,PreparedStatement pstm,
			ResultSet rs,String sql,Object[] params) throws Exception{
		//獲得preparedStatement物件
		pstm = connection.prepareStatement(sql);
		//將陣列中的陣列元素依次放入pstm中
		for(int i = 0; i < params.length; i++){
			pstm.setObject(i+1, params[i]);
		}
		//呼叫無參查詢方法,得到結果集
		rs = pstm.executeQuery();
		return rs;
	}
	/**
	 * 更新操作
	 * @param connection
	 * @param pstm
	 * @param sql
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static int execute(Connection connection,PreparedStatement pstm,
			String sql,Object[] params) throws Exception{
		int updateRows = 0;
		pstm = connection.prepareStatement(sql);
		for(int i = 0; i < params.length; i++){
			pstm.setObject(i+1, params[i]);
		}
		updateRows = pstm.executeUpdate();
		return updateRows;
	}
	
	/**
	 * 釋放資源
	 * @param connection
	 * @param pstm
	 * @param rs
	 * @return
	 */
	public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){
		boolean flag = true;
		if(rs != null){
			try {
				rs.close();
				rs = null;//GC回收
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag = false;
			}
		}
		if(pstm != null){
			try {
				pstm.close();
				pstm = null;//GC回收
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag = false;
			}
		}
		if(connection != null){
			try {
				connection.close();
				connection = null;//GC回收
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag = false;
			}
		}
		
		return flag;
	}

}

UserDao.java

package cn.kgc.dao;

import java.sql.Connection;

import cn.kgc.pojo.User;

public interface UserDao {
	public User getLoginUser(Connection connection,String userCode)throws Exception;
}

UserDaoImpl.java

package cn.kgc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.springframework.stereotype.Repository;

import cn.kgc.pojo.User;
@Repository
public class UserDaoImpl implements UserDao {

	@Override
	public User getLoginUser(Connection connection, String userCode)
			throws Exception {
		// TODO Auto-generated method stub
		PreparedStatement pstm=null;
		ResultSet rs=null;
		User user=null;
		if(connection!=null){
			String sql="select * from smbms_user where userCode=?";
			Object[] params={userCode};
			
			rs=BaseDao.execute(connection, pstm, rs, sql, params);
			System.out.println(rs);
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt("id"));
				user.setUserCode(rs.getString("userCode"));
				user.setUserName(rs.getString("userName"));
				user.setUserPassword(rs.getString("userPassword"));
				user.setGender(rs.getInt("gender"));
				user.setBirthday(rs.getDate("birthday"));
				user.setPhone(rs.getString("phone"));
				user.setAddress(rs.getString("address"));
				user.setUserRole(rs.getInt("userRole"));
				user.setCreatedBy(rs.getInt("createdBy"));
				user.setCreationDate(rs.getTimestamp("creationDate"));
				user.setModifyBy(rs.getInt("modifyBy"));
				user.setModifyDate(rs.getTimestamp("modifyDate"));
				
			}
			BaseDao.closeResource(null, pstm, rs);
		}
		return user;
	}

}

User.java

package cn.kgc.pojo;

import java.util.Date;

public class User {
   
	    private Integer id;           // id
	    private String  userCode;     // 使用者編碼
	    private String  userName;     // 使用者名稱稱
	    private String  userPassword; // 使用者密碼
	    private Integer gender;       // 性別
	    private Date    birthday;     // 出生日期
	    private String  phone;        // 電話
	    private String  address;      // 地址
	    private Integer userRole;     // 使用者角色ID
	    private Integer createdBy;    // 建立者
	    private Date    creationDate; // 建立時間
	    private Integer modifyBy;     // 更新者
	    private Date    modifyDate;   // 更新時間
	    private String  userRoleName; // 使用者角色名稱
	    
	    
	    public User(){}


		public User(Integer id, String userCode, String userName,
				String userPassword, Integer gender, Date birthday,
				String phone, String address, Integer userRole,
				Integer createdBy, Date creationDate, Integer modifyBy,
				Date modifyDate, String userRoleName) {
			super();
			this.id = id;
			this.userCode = userCode;
			this.userName = userName;
			this.userPassword = userPassword;
			this.gender = gender;
			this.birthday = birthday;
			this.phone = phone;
			this.address = address;
			this.userRole = userRole;
			this.createdBy = createdBy;
			this.creationDate = creationDate;
			this.modifyBy = modifyBy;
			this.modifyDate = modifyDate;
			this.userRoleName = userRoleName;
		}


		public Integer getId() {
			return id;
		}


		public String getUserCode() {
			return userCode;
		}


		public String getUserName() {
			return userName;
		}


		public String getUserPassword() {
			return userPassword;
		}


		public Integer getGender() {
			return gender;
		}


		public Date getBirthday() {
			return birthday;
		}


		public String getPhone() {
			return phone;
		}


		public String getAddress() {
			return address;
		}


		public Integer getUserRole() {
			return userRole;
		}


		public Integer getCreatedBy() {
			return createdBy;
		}


		public Date getCreationDate() {
			return creationDate;
		}


		public Integer getModifyBy() {
			return modifyBy;
		}


		public Date getModifyDate() {
			return modifyDate;
		}


		public String getUserRoleName() {
			return userRoleName;
		}


		public void setId(Integer id) {
			this.id = id;
		}


		public void setUserCode(String userCode) {
			this.userCode = userCode;
		}


		public void setUserName(String userName) {
			this.userName = userName;
		}


		public void setUserPassword(String userPassword) {
			this.userPassword = userPassword;
		}


		public void setGender(Integer gender) {
			this.gender = gender;
		}


		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}


		public void setPhone(String phone) {
			this.phone = phone;
		}


		public void setAddress(String address) {
			this.address = address;
		}


		public void setUserRole(Integer userRole) {
			this.userRole = userRole;
		}


		public void setCreatedBy(Integer createdBy) {
			this.createdBy = createdBy;
		}


		public void setCreationDate(Date creationDate) {
			this.creationDate = creationDate;
		}


		public void setModifyBy(Integer modifyBy) {
			this.modifyBy = modifyBy;
		}


		public void setModifyDate(Date modifyDate) {
			this.modifyDate = modifyDate;
		}


		public void setUserRoleName(String userRoleName) {
			this.userRoleName = userRoleName;
		}
	    
	    
		
}

UserService.java

package cn.kgc.service;

import cn.kgc.pojo.User;

public interface UserService {
	 //使用者登入
	public User login(String userCode,String userPassword);
}

UserServiceImpl.java

package cn.kgc.service;

import java.sql.Connection;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.kgc.dao.BaseDao;
import cn.kgc.dao.UserDao;
import cn.kgc.pojo.User;
@Service
public class UserServiceImpl implements UserService {
     
	     @Resource
	     private UserDao userDao;
	 
	@Override
	public User login(String userCode, String userPassword) {
		// TODO Auto-generated method stub
		Connection connection=null;
		User user=null;
		try{
			connection=BaseDao.getConnection();
			user=userDao.getLoginUser(connection,userCode);
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			BaseDao.closeResource(connection, null, null);
		}
		if(user!=null){
			//匹配密碼
			if(!user.getUserPassword().equals(userPassword)){
				user=null;
			}
		}
		
	return user;
	}

}

ConfigManager.java

package cn.kgc.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

//讀取配置檔案的工具類-單例模式
public class ConfigManager {
	private static ConfigManager configManager = new ConfigManager();
	private static Properties properties;
	//私有構造器-讀取資料庫配置檔案
	private ConfigManager(){
		String configFile = "database.properties";
		properties = new Properties();
		InputStream is = 
				ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
		try {
			properties.load(is);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/*//全域性訪問點-(懶漢模式)
	public static synchronized ConfigManager getInstance(){
		if(configManager == null){
			configManager = new ConfigManager();
		}
		return configManager;
	}*/
	
	//餓漢模式
	public static ConfigManager getInstance(){
		return configManager;
	}
	
	public String getValue(String key){
		return properties.getProperty(key);
	}
}

Constans.java

package cn.kgc.tools;

public class Constans {
      public final static String USER_SESSION="userSession";
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>系統登入 - 超市訂單管理系統</title>
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css" />
    <script type="text/javascript">
	/* if(top.location!=self.location){
	      top.location=self.location;
	 } */
    </script>
</head>
<body class="login_bg">
    <section class="loginBox">
        <header class="loginHeader">
            <h1>超市訂單管理系統</h1>
        </header>
        <section class="loginCont">
	        <form class="loginForm" action="${pageContext.request.contextPath }/user/dologin.html"  name="actionForm" id="actionForm"  method="post" >
				<div class="info">${error }</div>
				<div class="inputbox">
                    <label for="user">使用者名稱:</label>
					<input type="text" class="input-text" id="userCode" name="userCode" placeholder="請輸入使用者名稱" required/>
				</div>	
				<div class="inputbox">
                    <label for="mima">密碼:</label>
                    <input type="password" id="userPassword" name="userPassword" placeholder="請輸入密碼" required/>
                </div>	
				<div class="subBtn">
					
                    <input type="submit" value="登入"/>
                    <input type="reset" value="重置"/>
                </div>	
			</form>
        </section>
    </section>
</body>
</html>

frame.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/head.jsp"%>
<!-- /WEB-INF/jsp/ -->
    <div class="right">
        <img class="wColck" src="${pageContext.request.contextPath }/statics/images/clock.jpg" alt=""/>
        <div class="wFont">
            <h2>${userSession.userName }</h2>
            <p>歡迎來到超市訂單管理系統!</p>
        </div>
    </div>
</section>
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>