Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作

目录

1、pojo层:实体类层

2、Dao层,写数据库操作的包。

        (1)首先配置数据库文件,创建db.properties文件

        (2)编写基础公共类BaseDao (通用)

        (3)首先编写dao层登录用户登录的接口

        (4)编写dao接口的实现类

3、service层,调用Dao层进行业务实现(用户登录操作)

        (1)编写业务层接口

        (2)编写业务层业务层实现类

4、servlet层操作(接收用户页面参数,调用service层,转发视图)

5、filter层(过滤器层)

        (1)编写字符编码过滤器

        (2)编写页面权限过滤器

6、别忘了servlet和filter要在web.xml里面注册

Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作_第1张图片

1、pojo层:实体类层

        主要就是编写实体类,私有属性,无参构造,set和get方法,tostring

package com.zhou.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; // 用户角色

    private Integer createdBy; // 创建者

    private Date creationDate; // 创建时间

    private Integer modifyBy; // 更新者

    private Date modifyDate; // 更新时间

    private Long age; // 年龄

    private String userRoleName; // 用户角色名称

    public String getUserRoleName(){

        return userRoleName;

    }

    public void setUserRoleName(String userRoleName){

        this.userRoleName = userRoleName;

    }

    public long getAge(){

        Date date = new Date();

        long age = date.getYear() - birthday.getTime();

        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;

    }

}

2、Dao层,写数据库操作的包。

        目录结构:

                Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作_第2张图片

        (1)首先配置数据库文件,创建db.properties文件

        (2)编写基础公共类BaseDao (通用)

                (封装好,以后可以一直用,包括,连接数据库,查询数据库,增删改数据库,关闭连接)

package com.zhou.dao;

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

            throw new RuntimeException(e);

        }

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

            throw new RuntimeException(e);

        }

        return connection;

    }

    // 编写查询公共类

    public static ResultSet execute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {

        // 预编译的sql,在后面直接执行就可以了

        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {

            // setObject 占位符从1开始,但是我们的数组是从0开始

            preparedStatement.setObject(i+1, params[i]);

        }

        resultSet = preparedStatement.executeQuery();

        return resultSet;

    }

    // 编写增删改公共方法

    public static int execute(Connection connection, String sql, Object[] params, PreparedStatement preparedStatement) throws SQLException {

        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {

            // setObject 占位符从1开始,但是我们的数组是从0开始

            preparedStatement.setObject(i+1, params[i]);

        }

        int updateRows = preparedStatement.executeUpdate();

        return updateRows;

    }

    // 释放资源

    public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){

        boolean flag = true;

        if (resultSet != null){

            try {

                resultSet.close();

                // GC回收

                resultSet = null;

            } catch (SQLException e) {

                e.printStackTrace();

                flag = false;

            }

        }

        if (preparedStatement != null){

            try {

                preparedStatement.close();

                // GC回收

                preparedStatement = null;

            } catch (SQLException e) {

                e.printStackTrace();

                flag = false;

            }

        }

        if (connection != null){

            try {

                connection.close();

                // GC回收

                connection = null;

            } catch (SQLException e) {

                e.printStackTrace();

                flag = false;

            }

        }

        return flag;

    }

}

        (3)首先编写dao层登录用户登录的接口

package com.zhou.dao.user;

import com.zhou.pojo.User;

import java.sql.Connection;

import java.sql.SQLException;

public interface UserDao {

    // 得到要登录的用户

    public User getLoginUser(Connection connection, String userCode) throws SQLException;

}

        (4)编写dao接口的实现类

package com.zhou.dao.user;

import com.zhou.dao.BaseDao;

import com.zhou.pojo.User;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao{

    // 得到要登录的用户

    public User getLoginUser(Connection connection, String userCode) throws SQLException {

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

            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.closeResource(null, pstm, rs);

        }

        return user;

    }

}

3、service层,调用Dao层进行业务实现(用户登录操作)

        (1)编写业务层接口

package com.zhou.service.user;

import com.zhou.pojo.User;

public interface UserService {

    //用户登录

    public User login(String userCode, String password);

}

        (2)编写业务层业务层实现类

package com.zhou.service.user;

import com.zhou.dao.BaseDao;

import com.zhou.dao.user.UserDao;

import com.zhou.dao.user.UserDaoImpl;

import com.zhou.pojo.User;

import org.junit.Test;

import java.sql.Connection;

import java.sql.SQLException;

public class UserServiceImpl implements UserService{

    //业务层都会调用dao层,所以我们要引入Dao层

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

        } catch (SQLException e) {

            throw new RuntimeException(e);

        }finally {

            BaseDao.closeResource(connection, null, null);

        }

        return user;

    }

    @Test

    public void test(){

        UserServiceImpl userService = new UserServiceImpl();

        User admin = userService.login("wen", "1234567");

        System.out.println(admin.getUserPassword());

    }

}

4、servlet层操作(接收用户页面参数,调用service层,转发视图)

package com.zhou.servlet.user;

import com.zhou.pojo.User;

import com.zhou.service.user.UserService;

import com.zhou.service.user.UserServiceImpl;

import com.zhou.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 {

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

    @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);

    }

}

Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作_第3张图片

5、filter层(过滤器层)

        (1)编写字符编码过滤器

package com.zhou.filter;

import javax.servlet.*;

import java.io.IOException;

public class CharacterEncodingFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        servletRequest.setCharacterEncoding("utf-8");

        servletResponse.setCharacterEncoding("utf-8");

        servletResponse.setContentType("text/html;charset=utf-8");

        filterChain.doFilter(servletRequest, servletResponse);

    }

    public void destroy() {

    }

}

        (2)编写页面权限过滤器

                (配合用户退出功能做的,用户退出后,也就是session被清除了就不可以不登录就直接进一些网页)

package com.zhou.filter;

import com.zhou.pojo.User;

import com.zhou.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 filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) resp;

        // 过滤器从session中获取用户,如果session被移除了,(LoginOutServlet)那就获取不到user了

        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        if (user == null){ // 已经被移除或者注销,或者未登录

            response.sendRedirect("/smbms/error.jsp");

        }else {

            filterChain.doFilter(req, resp);

        }

    }

    public void destroy() {

    }

}

6、别忘了servlet和filter要在web.xml里面注册

Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作_第4张图片

Maven的Web项目中pojo层、Dao层、service层、servlet层、filter层实现一次登录操作_第5张图片 

 

你可能感兴趣的:(学习,java,maven,数据库)