Java Web总结十三之一用户登录与注册

一、用户登录与注册使用了如下技术:

1、Jsp+Servlet+JavaBean+Jdbc+Mysql+DAO单例工厂设计模式+属性文件配置。

2、在JavaBean中注册了日期转化函数。

3、MySql的日期类型与Java的日期类型之间的处理。

二、类结构图和需导入的包如下图所示:

三、具体代码

1、DbConfig.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mydb3
user=root
password=root

2、IUserDao.java:

package com.gnnuit.web.login.dao;

import com.gnnuit.web.login.domain.UserInfo;

public interface IUserDao {
    // 查询用户名、密码是否存在
    public boolean find(String username, String password);

    // 增加用户
    public boolean add(UserInfo userinfo);
}

3、UserDao.java:

package com.gnnuit.web.login.dao;

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

import com.gnnuit.web.login.domain.UserInfo;
import com.gnnuit.web.login.util.JDBCUtil;

public class UserDao implements IUserDao {

    @Override
    public boolean find(String username, String password) {
        boolean flag = false;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "select * from user where username=? and password=?";
        try {
            conn = JDBCUtil.getMySqlConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(rs);
            JDBCUtil.close(pstmt);
            JDBCUtil.close(conn);
        }
        return flag;
    }

    @Override
    public boolean add(UserInfo userinfo) {
        boolean flag = false;
        Connection conn = null;
        PreparedStatement pstmt = null;
        String sql = "insert into user(username,password,birthday,salary) values(?,?,?,?)";
        try {
            conn = JDBCUtil.getMySqlConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userinfo.getUsername());
            pstmt.setString(2, userinfo.getPassword());
            pstmt.setDate(3,
                    new java.sql.Date(userinfo.getBirthday().getTime()));
            pstmt.setInt(4, userinfo.getSalary());
            pstmt.executeUpdate();
            flag = true;
        } catch (Exception e) {

        } finally {
            JDBCUtil.close(conn);
            JDBCUtil.close(pstmt);
        }
        return flag;
    }

}

4、user.sql:

drop table if exists user;
create table if not exists user(
    id INTEGER primary key auto_increment,
    username VARCHAR(100) not null,
    password VARCHAR(100) not null,
    birthday DATE,
    salary INTEGER    
);
insert into user(username,password) values('jack','000000');
insert into user(username,password) values('marry','111111');

5、UserInfo.java:

package com.gnnuit.web.login.domain;

import java.util.Date;


public class UserInfo {
    private String username;
    private String password;
    private Date birthday;
    private int salary;

    public UserInfo() {

    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

}

6、DaoFactory.java:

package com.gnnuit.web.login.factory;

import com.gnnuit.web.login.dao.IUserDao;
import com.gnnuit.web.login.dao.UserDao;

//访问数据库的工厂(单例)
public class DaoFactory {
    private DaoFactory() {

    }

    private static DaoFactory daoFactory;

    public static DaoFactory getDaoFactory() {
        if (daoFactory == null) {
            daoFactory = new DaoFactory();
        }
        return daoFactory;
    }

    public IUserDao getUserDao() {
        return new UserDao();
    }
}

7、UserService.java:

package com.gnnuit.web.login.service;

import com.gnnuit.web.login.dao.IUserDao;
import com.gnnuit.web.login.domain.UserInfo;
import com.gnnuit.web.login.factory.DaoFactory;

public class UserService {
    private IUserDao dao = DaoFactory.getDaoFactory().getUserDao();

    public boolean login(String username, String password) {
        boolean flag = false;
        flag = dao.find(username, password);
        return flag;
    }

    public boolean register(UserInfo userinfo) {
        boolean flag = false;
        flag = dao.add(userinfo);
        return flag;
    }
}

8、JDBCUtil.java:

package com.gnnuit.web.login.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public final class JDBCUtil {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    // 静态块:加载配置文件
    static {
        Properties prop = new Properties();
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream(
                "com/gnnuit/web/login/config/DbConfig.properties");
        try {
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 静态块:注册驱动
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取MySql数据库的连接
    public static Connection getMySqlConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    // 关闭数据库
    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

9、UserServlet.java:

package com.gnnuit.web.login.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Locale;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.gnnuit.web.login.domain.UserInfo;
import com.gnnuit.web.login.service.UserService;

public class UserServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("method");
        if (method != null) {
            if ("login".equals(method)) {
                login(request, response);
            } else if ("register".equals(method)) {
                register(request, response);
            }
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = new UserService();
        boolean flag = userService.login(username, password);
        if (flag) {
            request.setAttribute("message", "登录成功");
        } else {
            request.setAttribute("message", "登录失败");
        }
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

    private void register(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        UserInfo userinfo = new UserInfo();
        Enumeration<String> names = request.getParameterNames();
        ConvertUtils.register(new DateLocaleConverter(Locale.getDefault(),
                "yyyy-MM-dd"), java.util.Date.class);
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            try {
                BeanUtils.setProperty(userinfo, name,
                        request.getParameterValues(name));
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        UserService userService = new UserService();
        boolean flag = userService.register(userinfo);
        if (flag) {
            request.setAttribute("message", "注册成功");
        } else {
            request.setAttribute("message", "注册失败");
        }
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
}

10、login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

  </head>
  
  <body>
    <form action="/day13/UserServlet?method=login" method="post">
        <table align="center">
            <caption>登录</caption>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>
    </form>
  </body>
</html>

11、message.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'message.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
  </head>
  
  <body>
    ${message}
  </body>
</html>

12、register.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'register.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

  </head>
  
  <body>
    <form action="/day13/UserServlet?method=register" method="post">
        <table align="center" border="1">
            <caption>注册</caption>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td>生日</td>
                <td><input type="text" name="birthday"/></td>
            </tr>
            <tr>
                <td>期望薪水</td>
                <td><input type="text" name="salary"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>
    </form>
  </body>
</html>
原文地址:https://www.cnblogs.com/FlySheep/p/3659404.html