Java 实现用户登录项目

Java 实现用户登录项目

需求:

在页面中要求输入用户名和密码,并显示验证码。在三项都通过验证后显示登录成功否则登录失败

分析;

  1. 在验证用户名密码之前应该先判断验证码是否通过验证,防止多次连接数据库校验
  2. 可以将用户名密码封装为一个对象传入数据库,并在Dao层定义一个方法用于接收数据库的返回对象。如果对象不为Null则表示登录成功,如果返回值为null则在页面显示用户名或密码错误。
  3. 连接数据库可以用Druid来管理线程池

1. 制作验证码:

@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();

        // 用颜色填充出一块底色为粉红色的长方形
        graphics.setColor(Color.PINK);
        graphics.fillRect(0,0,width,height);

        // 画出长方形的边框
        graphics.setColor(Color.BLACK);
        graphics.drawRect(0,0,width-1,height-1);

        // 生成随机数字取得字符并画出
        Random wordRandom = new Random();
        String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i <=4 ; i++) {
            int index = wordRandom.nextInt(word.length()-1);
            char code = word.charAt(index);
            stringBuilder.append(code);
            graphics.drawString(code+" ", width/5*i, height/2);
        }
        String checkcode = stringBuilder.toString();
        // 将验证码发送到session方便以后的验证
        request.getSession().setAttribute("checkcode_session", checkcode);
        graphics.setColor(Color.GREEN);

        // 生成随机点画出10条线
        for (int i=0; i<10;i++){
            int x1 = wordRandom.nextInt(width);
            int x2 = wordRandom.nextInt(width);
            int y1 = wordRandom.nextInt(height);
            int y2 = wordRandom.nextInt(height);

            graphics.drawLine(x1,y1,x2,y2);
        }
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

2. 定义User类来封装User数据

public class User {
    private int id;
    private String username, password;

    public int getId() {
        return id;
    }

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

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

定义JDBC工具类

public class JDBCutils{
	private static DataSource datasource;
	static{
		try{
			Properties properties = new Properties(); // 使用Properties.load()导入druid.properties的流文件
			InputSteam inputStream = JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties");
			properties.load(inputSteam);
		}catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	public DataSource getDataSource(){return datasource;}
	public Connection getConnection(){return datasource.getConnection();}
}

在Dao层完成数据库的验证

public class Dao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCutils.getDataSource());

    public User login(User login_user){

        try {
            String name = login_user.getUsername();
            String password = login_user.getPassword();

            String sql = "select * from user where username = ? and password =?";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), name, password);
        } catch (DataAccessException e){
            e.printStackTrace();
            return null;
        }

    }
}

在完成Dao层后应该可以编写一个Test类来测试SQL语句是否能正常的运行

定义页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Login</title>
  </head>
  <script>
    window.onload = function () {
      document.getElementById("check").onclick = function(){
        this.src = "/Login/CheckCode?time=" + new Date().getTime();
      }
    }


  </script>

<style>
  div{
    color: red;
  }
</style>



  <body>
  <form action="/Login/LoginServlet" method="post">
    <table>
      <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="checkcode"></td>
      </tr>

      <tr>
        <td colspan="2"><img id="check" src="/Login/CheckCode" > </td>
      </tr>

      <tr>
        <td colspan="2"><input type="submit" value="登录"></td>
      </tr>

    </table>
  </form>

  <div>
    <%=request.getAttribute("checkcode_error")==null?" ":request.getAttribute("checkcode_error")%>
  </div>
  <div>
    <%=request.getAttribute("login_error")==null?" ":request.getAttribute("login_error")%>
  </div>
  </body>
</html>

完成LoginServlet

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 获取参数
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkcode = request.getParameter("checkcode");
        // 获得从CheckCode发送来的session信息
        String checkcode_session =(String) session.getAttribute("checkcode_session");
		// 移除session信息保证每次的验证码不会重复
        session.removeAttribute("checkcode_session");
        if (checkcode_session!=null && checkcode_session.equalsIgnoreCase(checkcode)){
            User loguser = new User();
            loguser.setUsername(username);
            loguser.setPassword(password);
            Dao dao = new Dao();
            User user = dao.login(loguser);

            if (user!=null){
                session.setAttribute("user", username);
                response.sendRedirect(request.getContextPath() + "/success.jsp");
            }
            else{
                request.setAttribute("login_error", "用户名或密码错误");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }
        }else{
            // 如果不一致存储信息到request
            request.setAttribute("checkcode_error", "验证码错误");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值