会话技术 cookie session jsp 验证码案例

news/2024/5/18 11:49:08 标签: java, tomcat, cookie, session, http
http://www.w3.org/2000/svg" style="display: none;">

案例需求

访问带有验证码的登录界面login.jsp

用户输入用户名,密码以及验证码

  • 如果用户名和密码输入有误, 跳转登录页面:提示用户名或密码错误
  • 如果输入验证码有误, 跳转登录页面, 提示验证码错误
  • 如果全部输入正确, 则跳转主页success.jsp, 显示: 用户名,欢迎您~~

分析

https://img-blog.csdnimg.cn/ecbd276d8ca2407bbc6239cf4e69f606.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56i755Sw6YeM5bGV5pyb6ICF,size_20,color_FFFFFF,t_70,g_se,x_16" alt="在这里插入图片描述" />

代码实现

登录页面login.jsp页面

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


    <script>javascript">
        window.onload = function(){
            document.getElementById("img").onclick = function(){
                this.src="/checkCodeServlet?time="+new Date().getTime();
            }
        }


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

    </style>
</head>
<body>

    <form action="/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="img" src="/checkCodeServlet"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="登录"></td>
            </tr>
        </table>


    </form>


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

</body>
</html>


登录成功的页面success.jsp

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

    <h1><%=request.getSession().getAttribute("user")%>,欢迎您</h1>

</body>
</html>


验证码Servlet类CheckCodeServlet

java">package servlet;

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;

        //1.创建一对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


        //2.美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.fillRect(0,0,width,height);

        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            sb.append(ch);

            //2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        //将验证码存入session
        request.getSession().setAttribute("checkCode_session",checkCode_session);

        //2.4画干扰线
        g.setColor(Color.GREEN);

        //随机生成坐标点

        for (int i = 0; i < 10; 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);
        }


        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());


    }

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


登录Servlet类LoginServlet

java">package servlet;

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 {
        //1.设置request编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        //3.先获取生成的验证码
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //删除session中存储的验证码
        session.removeAttribute("checkCode_session");
        //3.先判断验证码是否正确
        if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkCode)){
            //忽略大小写比较
            //验证码正确
            //判断用户名和密码是否一致
            if("zhangsan".equals(username) && "123".equals(password)){//需要调用UserDao查询数据库
                //登录成功
                //存储信息,用户信息
                session.setAttribute("user",username);
                //重定向到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("cc_error","验证码错误");
            //转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }

    }

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

启动

https://img-blog.csdnimg.cn/af73bd08f2cd438fae1b5d0fcf68af2b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56i755Sw6YeM5bGV5pyb6ICF,size_20,color_FFFFFF,t_70,g_se,x_16" alt="在这里插入图片描述" />

https://img-blog.csdnimg.cn/058c92c0ae604d758783f038eecbd8c4.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56i755Sw6YeM5bGV5pyb6ICF,size_19,color_FFFFFF,t_70,g_se,x_16" alt="在这里插入图片描述" />


http://www.niftyadmin.cn/n/1782348.html

相关文章

MVC 概述

概念 M — Model — 模型 ---- 完成具体的业务操作( 查询数据库 , 封装对象 ) V — View — 试图 ---- 展示数据 C — Controller — 控制器 ---- 获取用户输入 , 调用模型 , 将数据交给视图进行展示 原理示意图 优点 耦合性低 — 方便维护, 可以利于分工协作 重用性高 缺…

linux cp 复制文件夹

复制文件夹需要添加 -r 或 -R 参数&#xff08;recursive: 递归的&#xff1b;循环的&#xff09; 如 cp -r DIR_A DIR_B; 同理&#xff0c;rm 也一样。 如 rm -r DIR_B

MDX Cookbook 01 - Skipping Axis 合理使用空的 SET 集合获取全部层次结构成员

假设我们只想显示一些与数据没有任何关联的维度成员信息&#xff0c;并且希望它们能够以行集的形式来显示&#xff0c;那么在 MDX 中就应该直接显示 ROWS AXIS (1) 并且忽略掉 COLUMNS AXIS(0)。比如说有100个成员信息&#xff0c;如果是一列100行的形式通常符合大家的查询习惯…

Javascript中的一些自有方法

Javascript中的一些方法&#xff1a; 1、 JavaScript中settimeout与setinteval两个函数的区别&#xff1f;settimeout只执行一次&#xff08;页面加载之后在给定的时间里执行一次&#xff0c;如果需要执行多次&#xff0c;可以把该事件写入调用被触发方法内部&#xff0c;以便循…

弹出对话框+背景为灰色

比如像这样的页面&#xff0c;前段时间自己在写的时候不是很会&#xff0c;然后问了学姐&#xff0c;然后自己上网查找了下资料。然后知道了这样的写法。上面是这样的效果。 讲解&#xff1a; 在上面点击第二张中的“点击获取优惠券”然后弹出这样的对话框&#xff0c;背景变成…

三层架构 : 软件设计架构

界面层(表示层)&#xff1a;用户看的得界面。用户可以通过界面上的组件和服务器进行交互业务逻辑层&#xff1a;处理业务逻辑的。数据访问层&#xff1a;操作数据存储文件。 来源:黑马程序员

大话it职场之经历风雨是否能见彩虹

不经历风雨&#xff0c;怎么能见彩虹&#xff1f;这句话大家都知道什么意识。可是经历了风雨真的能见彩虹吗&#xff1f;可以肯定的说&#xff0c;不经历风雨肯定见不到&#xff0c;经历了也不一定。为什么这么说呢&#xff1f; 看看我们这行的从业者&#xff0c;每年有多少人进…

C语言 线性表 双向链式结构 实现

一个双向链式结构实现的线性表 duList (GCC编译)。 1 /**2 * brief 线性表双向链表结构3 * author wid4 * date 2013-10-285 *6 * note 若代码存在 bug 或程序缺陷, 请留言反馈, 谢谢!7 */8 9 #include <stdio.h>10 #include <stdlib.h>11 12 #define TRUE 113 #de…