zoukankan      html  css  js  c++  java
  • 我爱Java系列---【案例:使用session存储验证码完成登录功能】

    image

    案例需求

    1. 在登录页面用户登录的时候要查看到验证码,如图所示:

    2. 在生成页面验证码图片的同时,使用session存储验证码

    3. 在处理用户登录请求的时候,首先校验验证码

    4. 校验通过才能执行登录操作

    案例分析

    image

    代码实现:

    1.页面代码

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>login</title>
    <script type="text/javascript">
    function changeCode(){
    document.getElementById("img").src = "/day04/checkcode?r="+new
    Date().getTime();
    }
    </script>
    </head>
    <body>
    <form action="/day04/login" 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="code"></td></tr>
    <!-- 通过向服务器发送请求,从服务器获取验证码数据 -->
    <tr><td></td><td><img id="img" src="/day04/checkcode"
    onclick="changeCode();"/><a href="javascript:;" onclick="changeCode();">换一换</a>
    <span><% if(request.getAttribute("msg")!=null)
    {out.write(request.getAttribute("msg").toString());}%></span></td></tr>
    <tr><td></td><td><input type="submit" value="登陆"></td></tr>
    </table>
    </form>
    </body>
    </html>

    2. 配置验证码servlet

    @WebServlet(name = "CheckcodeServlet",urlPatterns = "/checkcode")

    public class CheckcodeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    // 创建画布

    int width = 120;

    int height = 40;

    BufferedImage bufferedImage = new BufferedImage(width, height,

    BufferedImage.TYPE_INT_RGB);

    // 获得画笔

    Graphics g = bufferedImage.getGraphics();

    // 填充背景颜色

    g.setColor(Color.white);

    g.fillRect(0, 0, width, height);

    // 绘制边框

    g.setColor(Color.red);

    g.drawRect(0, 0, width - 1, height - 1);

    // 生成随机字符3. 登录servlet

    // 准备数据

    String data =

    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

    // 准备随机对象

    Random r = new Random();

    // 声明一个变量 保存验证码

    String code = "";

    // 书写4个随机字符

    for (int i = 0; i < 4; i++) {

    // 设置字体

    g.setFont(new Font("宋体", Font.BOLD, 28));

    // 设置随机颜色

    g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

    String str = data.charAt(r.nextInt(data.length())) + "";

    g.drawString(str, 10 + i * 28, 30);

    // 将新的字符 保存到验证码中

    code = code + str;

    }

    // 绘制干扰线

    for (int i = 0; i < 6; i++) {

    // 设置随机颜色

    g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

    g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width),

    r.nextInt(height));

    }

    // 将验证码 打印到控制台

    System.out.println(code);

    // 将验证码放到session中

    request.getSession().setAttribute("code_session", code);

    // 将画布显示在浏览器中

    ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    doGet(request, response);

    }

    }

    3. 登录servlet

    @WebServlet(name = "LoginServlet",urlPatterns = "/login")

    public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {4. dao:

    //用户请求中的验证码获取

    String code = request.getParameter("code");

    //获取session中保存的验证码

    String code_session =

    (String)request.getSession().getAttribute("code_session");

    //与session中保存的验证码进行校验

    if(!code_session.equalsIgnoreCase(code)){

    //验证码错误,告诉用户,页面提示

    request.setAttribute("msg","验证码错误");

    request.getRequestDispatcher("/login.jsp").forward(request,response);

    return;

    }

    //验证码正确,登录逻辑执行

    //获取用户名和密码

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

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

    //调用Service方法,登录用户

    UserDao userDao = new UserDao();

    User loginUser = userDao.login(username,password);

    if(loginUser == null){

    request.setAttribute("msg","用户名或则密码错误");

    request.getRequestDispatcher("/login.jsp").forward(request,response);

    return;

    }else{

    //登陆成功,跳转主页

    response.sendRedirect(request.getContextPath());

    return;

    }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    doGet(request, response);

    }

    }

    4. dao:

    public class UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**

    * 查询用户名和密码是否匹配的方法

    */

    @Override

    public User login(String username, String password) {

    String sql = "select * from user where username = ? and password = ?";

    try {

    User query = template.queryForObject(sql, new

    BeanPropertyRowMapper<User>(User.class), username,password);

    return query;

    }catch (Exception e){

    e.printStackTrace();

    return null;

    }

    }

    }

    session的与cookie的区别

    image

     

     

    愿你走出半生,归来仍是少年!
  • 相关阅读:
    《剑指Offer》算法题——“旋转数组”的最小数字
    驱动是如何运行的
    Logistic回归,梯度上升算法理论详解和实现
    Python 字符串前面加'r'
    Python中文编码问题(字符串前面加'u')
    最大长度回文子串(Manacher's algorithm)
    没有重复字符的子串的最大长度
    Python格式化输出
    python strip()函数和Split函数的用法总结
    Python中的sorted函数以及operator.itemgetter函数
  • 原文地址:https://www.cnblogs.com/hujunwei/p/10939673.html
Copyright © 2011-2022 走看看