javaweb项目中验证用户登录流程

一、数据库表

数据库

user类

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; // 用户角色
	private Integer createdBy; // 创建者
	private Date creationDate; // 创建时间
	private Integer modifyBy; // 更新者
	private Date modifyDate; // 更新时间
	private Integer age;// 年龄
	private String userRoleName; // 用户角色名称

	private String idPicPath; // 证件照路径

	private String workPicPath; // 工作证照片路径

	public String getIdPicPath() {
		return idPicPath;
	}

	public void setIdPicPath(String idPicPath) {
		this.idPicPath = idPicPath;
	}

	public String getWorkPicPath() {
		return workPicPath;
	}

	public void setWorkPicPath(String workPicPath) {
		this.workPicPath = workPicPath;
	}

	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) {
		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;
	}

	public String getUserRoleName() {
		return userRoleName;
	}

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

	public Integer getAge() {
		/*
		 * long time = System.currentTimeMillis()-birthday.getTime(); Integer age =
		 * Long.valueOf(time/365/24/60/60/1000).IntegerValue();
		 */
		Date date = new Date();
		Integer age = date.getYear() - birthday.getYear();
		return age;
	}

	public Integer getId() {
		return id;
	}

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

	public String getUserCode() {
		return userCode;
	}

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

	public String getUserName() {
		return userName;
	}

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

	public String getUserPassword() {
		return userPassword;
	}

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

	public Integer getGender() {
		return gender;
	}

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

	public Date getBirthday() {
		return birthday;
	}

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

	public String getPhone() {
		return phone;
	}

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

	public String getAddress() {
		return address;
	}

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

	public Integer getUserRole() {
		return userRole;
	}

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

	public Integer getCreatedBy() {
		return createdBy;
	}

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

	public Date getCreationDate() {
		return creationDate;
	}

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

	public Integer getModifyBy() {
		return modifyBy;
	}

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

	public Date getModifyDate() {
		return modifyDate;
	}

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

二、BaseDao

用来提取公共的数据库方法

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

public class BaseDao {

    private  static String driver;
    private  static String url;
    private  static String username;
    private  static String password;

    static {
        Properties properties= new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    //获得数据库连接
    public  static Connection getConnection(){
        Connection connection = null;

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }

    //编写一个查询公共类
    public  static ResultSet exexute(Connection connection,PreparedStatement ps,ResultSet rs,String sql,Object[] params) throws SQLException {

        ps = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        rs = ps.executeQuery();
        return rs;
    }

    //编写增删改公共方法
    public  static int exexute(Connection connection,PreparedStatement ps,String sql,Object[] params) throws SQLException {
        ps = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        int updateRows = ps.executeUpdate();
        return updateRows;
    }

    public static boolean closeResourse(Connection connection,PreparedStatement ps,ResultSet rs){
        Boolean flag = true;

        if(rs!=null){
            try {
                rs.close();
                //垃圾回收
                rs=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag =false;
            }
        }
        if(ps!=null){
            try {
                ps.close();
                //垃圾回收
                ps=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag =false;
            }
        }
        if(connection!=null){
            try {
                connection.close();
                //垃圾回收
                connection=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag =false;
            }
        }
        return false;
    }
}

db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/smbms?userUnicode=true&characterEncoding=utf-8
username = root
password = 123456

三、UserDao接口

import com.tt.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

public interface UserDao {

    public User getLoginUser(Connection connection, String usercode,String password) throws SQLException;
   }

UserDaoImpl

import com.mysql.jdbc.StringUtils;
import com.tt.dao.BaseDao;
import com.tt.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{

    //得到要登录的用户
    public User getLoginUser(Connection connection,String usercode,String password) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;

        if(connection!=null){
            String sql = "select * from smbms_user where userCode=? and userPassword=?";
            Object[] params = {usercode,password};

            rs = BaseDao.exexute(connection,ps,rs,sql,params);

            if(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.closeResourse(null,ps,rs);
        }
        return user;
    }
}

四、UserService接口

import com.tt.pojo.User;

public interface UserService {

    //用户登录
    public User login(String usercode,String password);
  }

UserServiceImpl

import com.tt.dao.BaseDao;
import com.tt.dao.user.UserDao;
import com.tt.dao.user.UserDaoImpl;
import com.tt.pojo.User;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService{

    private UserDao userdao;

    public UserServiceImpl(){
        userdao = new UserDaoImpl();
    }

    public User login(String usercode, String password) {
        Connection connection = null;
        User user = null;

        try {
            connection = BaseDao.getConnection();
            user = userdao.getLoginUser(connection, usercode,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResourse(connection,null,null);

        }
        return user;
    }

五、LoginServelet

package com.tt.servelet.user;

import com.tt.pojo.User;
import com.tt.service.user.UserService;
import com.tt.service.user.UserServiceImpl;
import com.tt.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet{

    //servelet:控制层,调用业务层代码

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet---start...");

        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //和数据库对比
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);

        if(user != null){//有此人
            //将用户信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转主页
            resp.sendRedirect("jsp/frame.jsp");
        }else{//无此人
            req.setAttribute("error","用户名或者密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

LoginOutServelet

package com.tt.servelet.user;

import com.tt.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginoutServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除session
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

六、Constants类

package com.tt.util;

public class Constants {
    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}/login.do"  name="actionForm" id="actionForm"  method="post" >
				<div class="info">${error}</div>
				<div class="inputbox">
                    <label for="userCode">用户名:</label>
					<input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
				</div>	
				<div class="inputbox">
                    <label for="userPassword">密码:</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>

syserror

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>请登录后再访问该页面!</h1>
<a href="${pageContext.request.contextPath }/login.jsp">返回</a>
</body>
</html>

八、过滤器

CharacterEncodingFilter 类:过滤中文乱码

package com.tt.filter;


import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter{
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}

SysFilter 类

package com.tt.filter;

import com.tt.pojo.User;
import com.tt.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter{
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //过滤器,从用户中取session
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        if (user == null){//被移除,注销,未登录
            response.sendRedirect(request.getContextPath()+"/syserror.jsp");
        }else {
            chain.doFilter(req,resp);
        }
    }

    public void destroy() {

    }
}

九、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        	        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         metadata-complete="true">

  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.tt.servelet.user.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>LoginoutServlet</servlet-name>
    <servlet-class>com.tt.servelet.user.LoginoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginoutServlet</servlet-name>
    <url-pattern>/jsp/logout.do</url-pattern>
  </servlet-mapping>


  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.tt.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
    <filter-name>SysFilter</filter-name>
    <filter-class>com.tt.filter.SysFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SysFilter</filter-name>
    <url-pattern>/jsp/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

  //默认session过期时间
<session-config>
  <session-timeout>30</session-timeout>
</session-config>
</web-app>

十、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>smbms</name>
  <groupId>com.tt</groupId>
  <artifactId>smbms</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>jstl-api</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/taglibs/standard -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.62</version>
    </dependency>


  </dependencies>

</project>

发布了23 篇原创文章 · 获赞 43 · 访问量 1381

猜你喜欢

转载自blog.csdn.net/qq_41256881/article/details/105330066