亲宝软件园·资讯

展开

JavaWeb 用户登录注册 JavaWeb简单用户登录注册实例代码(有验证码)

lungggg 人气:0

需求

jar包


技术选型
Servlet + JSP + Mysql + JDBCTemplate + Druid + BeanUtils + Tomcat

效果图

验证码或者用户名和密码错误

Navicat Premium 显示Mysql内容


登录成功

注册功能


源码

登录主界面 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Login</title>

  <script>
  <%-- 增加时间戳来更换验证码图片 --%>
    window.onload=function(){
      document.getElementById("img").onclick=function(){
        this.src = "/daydayup/checkCodeServlet?time" + new Date().getTime();
      }
    }
    
<%-- 用于打开注册的窗口--%>
    function reg() {
      window.open("register.jsp");
    }
  </script>
  <style>
    div{
      color: red;
    }
  </style>
</head>
<body>

<form action="/daydayup/loginServlet" method="post">
  <table>
    <tr>
      <td>用户名</td>
      <td><input type="text" name="username"></td>
    </tr>
    <tr>
      <td>密码</td>
      <td><input type="text" name="password"></td>
    </tr>
    <tr>
      <td>验证码</td>
      <td><input type="text" name="checkcode"></td>
    </tr>
    <tr>
      <td colspan="2"><img id="img" src="/daydayup/checkCodeServlet" alt=""></td>
    </tr>
    <tr>
      <td><input type="submit" value="登录"></td>
      <td><input type="button" value="注册" onclick="reg()" ></td>

    </tr>
  </table>
</form>

<div>${requestScope.login_error}</div>
<div>${requestScope.checkcode_error}</div>
</body>
</html>

注册界面 register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<form action="/daydayup/registerServlet" method="post">
  <table>
    <tr>
      <td>用户名</td>
      <td><input type="text" name="username"></td>
    </tr>
    <tr>
      <td>密码</td>
      <td><input type="text" name="password"></td>
    </tr>
    <tr>
      <td><input type="submit" value="确定注册"></td>
    </tr>
  </table>
</form>
<div>${requestScope.register_success}</div>
<div>${requestScope.register_error}</div>
</body>
</html>

成功界面 success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<%--  <h1>${requestScope.user},欢迎您</h1>  --%>
  <h1><%=request.getSession().getAttribute("user")%>,欢迎您</h1>
</body>
</html>

先编辑好JDBCUtils工具类

package cn.code.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类 使用Durid连接池
 */
public class JDBCUtils {

  private static DataSource ds;

  static{
    try {
      //加载配置文件
      Properties pro = new Properties();
      //使用ClassLoader加载配置文件,获取字节输入流
      InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
      pro.load(is);

      //初始化连接池对象
      ds = DruidDataSourceFactory.createDataSource(pro);
    } catch (Exception e) {
      e.printStackTrace();
    }


  }

  /**
   * 获取连接池对象
   */
  public static DataSource getDataSource(){
    return ds;
  }
  /**
   * 获取连接connection对象
   */
  public static Connection getConnection() throws SQLException {
    return ds.getConnection();
  }
}

创建我们的用户类实体User

package cn.code.domain;

/*
用户的实体类
 */

public class User {
  private int id ;
  private String username;
  private String 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 + '\'' +
        '}';
  }
}

编写Dao来操作数据库,里面有login和add两个方法 Userdao

package cn.code.dao;

import cn.code.domain.User;
import cn.code.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

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

/**
 * 操作数据库中User表的类
 */
public class UserDao {

  //声明JDBCTemplate对象,以便方法公用
  private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

  /**
   * 登录方法
   *
   * @param loginUser 目前只有用户名和密码
   * @return user包含用户全部数据
   */
  public User login(User loginUser) {
    //编写SQL
    String sql = "select * from user where username = ? and password = ?";
    //调用query方法
    try {
      User user = template.queryForObject(sql,
          new BeanPropertyRowMapper<User>(User.class),
          loginUser.getUsername(), loginUser.getPassword());
      return user;
    } catch (DataAccessException e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 注册方法
   *
   * @param user 目前只包含用户名和密码
   * @return 是否注册成功
   */
  public boolean add(User user){
    //编写SQL
    String sql = "insert into user (username,password) VALUES('" + user.getUsername() + "','" + user.getPassword() + "')";
    boolean flag = false;
    int num = 0;
    try {
      //创建数据库连接
      Connection conn = JDBCUtils.getConnection();
      Statement state = null;
      flag = false;
      num = 0;

      state = conn.createStatement();
      num = state.executeUpdate(sql);
    } catch (SQLException e) {
      e.printStackTrace();
    }

    if(num >0) flag = true;
    return flag;
  }
}

登录的Servlet

package cn.code.servlet;

import cn.code.dao.UserDao;
import cn.code.domain.User;

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

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //设置字符编码
    request.setCharacterEncoding("utf-8");
    //获取参数
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String checkcode = request.getParameter("checkcode");
    //获取生成的验证码
    HttpSession session = request.getSession();
    String checkcode_session =(String) session.getAttribute("checkcode_session");
    //防止验证码存储 删除Session中存储的验证码
    session.removeAttribute("checkcode_session");

    //判断验证码是否正确
    if(checkcode_session != null && checkcode_session.equalsIgnoreCase(checkcode)){
      //equalsIgnoreCase忽略大小写的比较
      //验证码正确
      User loginUser = new User();
      loginUser.setUsername(username);
      loginUser.setPassword(password);
      User user = new UserDao().login(loginUser);

      if(user != null){
        //用户名以及密码正确
        //登录成功
        //存储用户信息
        session.setAttribute("user",username); //因为是两次请求,所以用Session
        //重定向到success.jsp
        response.sendRedirect(request.getContextPath()+"/success.jsp");
      }else{
        //用户名及密码错误
        //登录失败
        //存储提示信息到request
        request.setAttribute("login_error","用户名或密码错误");
        //转发到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request,response);
      }
    }else{
      //验证码不正确
      //存储提示信息到request
      request.setAttribute("checkcode_error","验证码错误");
      //转发到登录页面
      request.getRequestDispatcher("/login.jsp").forward(request,response);
    }

  }

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

注册的Servlet

package cn.code.servlet;

import cn.code.dao.UserDao;
import cn.code.domain.User;

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

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");

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

    User registerUser = new User();
    registerUser.setUsername(username);
    registerUser.setPassword(password);
    boolean flag = new UserDao().add(registerUser);
    if(flag) {
      request.setAttribute("register_success","注册成功");
      request.getRequestDispatcher("/register.jsp").forward(request,response);
    }else{
      request.setAttribute("register_error","账号以被注册,注册失败");
      request.getRequestDispatcher("/register.jsp").forward(request,response);
    }

  }

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

在页面中画验证码(可点击更换)Servlet

package cn.code.checkcode;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

//简易验证码
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet 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 g = image.getGraphics();//画笔对象
    g.setColor(Color.ORANGE);
    g.fillRect(0,0,width,height);
    //画边框
    g.setColor(Color.BLUE);
    g.drawRect(0,0,width-1,height-1);

    String str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890zxcvbnmlkjhgfdsaqwertyuiop";

    //生成随机角标
    StringBuilder sb = new StringBuilder();
    Random ran = new Random();
    for (int i = 1; i <= 4; i++) {
      int index = ran.nextInt(str.length());
      //获取字符
      char ch = str.charAt(index);
      sb.append(ch);
      //写验证码
      g.drawString(ch+"",width/5*i,height/2);
    }
    String checkcode_session = sb.toString();
    //将验证码存入session
    request.getSession().setAttribute("checkcode_session",checkcode_session);

    //画干扰线
    g.setColor(Color.RED);
    //随机生成坐标点
    for (int i = 0 ;i<6;i++) {
      int x1 = ran.nextInt(width);
      int x2 = ran.nextInt(width);
      int y1 = ran.nextInt(height);
      int y2 = ran.nextInt(height);
      g.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);
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论