Servlet 实现登陆

登陆的流程图

1、编写操作数据库的公共类

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 (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
    return connection;
}

//编写查询公共类
public static ResultSet execute(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, String sql, Object[] params) throws SQLException {
    //预编译的SQL,后面直接执行
    preparedStatement = connection.prepareStatement(sql);

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

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

    for (int i = 0; i < params.length; i++) {
        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 throwables) {
            throwables.printStackTrace();
            flag=false;
        }
    }
    if (preparedStatement!=null){
        try {
            preparedStatement.close();
            //GC回收
            preparedStatement=null;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            flag = false;
        }
    }
    if (connection!=null){
        try {
            connection.close();
            //GC回收
            connection=null;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            flag = false;
        }
    }
    return flag;
}

2、登陆的 Dao 层

public User getLoginUser(Connection connection, String username) throws SQLException {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    User user = null;

    if (connection != null) {
        String sql = "select * from `user` where username=?";
        Object[] params = {username};

        rs = BaseDao.execute(connection, pstm, rs, sql, params);

        if (rs.next()){
            user = new User();
            user.setId(rs.getInt("id"));
            user.setUserName(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
        }

        BaseDao.closeResource(null,pstm,rs);

    }
    System.out.println("UserDao=>"+user);
    return user;
}

3、业务层都会调用 Dao 层,所以要引入 Da o层

private UserDao userDao;

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

4、登陆的 Service 层

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

    try {
        connection = BaseDao.getConnection();
        user = userDao.getLoginUser(connection, username);

    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        BaseDao.closeResource(connection, null, null);
    }
    System.out.println("UserService=>"+user);
    return user;
}

5、登陆的 Servlet

//Servlet:控制层,调用业务层代码
System.out.println("LoginServlet--start...");

String username = req.getParameter("username");
String password = req.getParameter("password");

System.out.println("username=>" + username);
System.out.println("password=>" + password);

//和数据库中的密码进行比对,调用业务层
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login(username, password);// 这里已经把登陆的人给查出来了

System.out.println("UserServlet=>" + user);
if (user != null && username.equals(user.getUserName()) && password.equals(user.getPassword())) {
    req.getSession().setAttribute(Constants.USER_SESSION, user);

    //跳转到内部网页
    resp.sendRedirect("jsp/success.jsp");
} else {
    req.setAttribute("error", "用户名或密码错误");
    req.getRequestDispatcher("/login.jsp").forward(req, resp);
}

6、过滤器

HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse) resp;

//没有登陆时或者退出登陆时,session 为null,这时通过过滤器重定向到 error 页面
if (request.getSession().getAttribute(Constants.USER_SESSION)==null){
    response.sendRedirect("/t/error.jsp");
}else {
    chain.doFilter(req,resp);
}
posted @   泡面喝完还有汤  阅读(71)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示