Servlet + Session 验证码登录

Servlet + Session 验证码登录

Maven下新建Module,选定WebApp,修改groupID,设置name=login_check_code

Project Structure
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lRMoB140-1594283791006)(G:\Github_code\md_photos\20200709160521847.png)]

修改web.xml文件


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


web-app>

webapp下新建css文件夹,放入css全局样式

Servlet + Session 验证码登录_第1张图片

登录界面:login.jsp

<%--
  Created by IntelliJ IDEA.
  User: PitYk
  Date: 2020/2/22
  Time: 11:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>




    
    
    
    管理员登录

    
    
    
    
    
    
    


管理员登录


登录成功页面:success.jsp

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

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

body>
html>

验证码生成CheckCodeServlet

package main.com.web;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入CheckCodeServlet代码文件!");
        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        //在内存中创建一个长80,宽30的图片,默认黑色背景
        //参数一:长
        //参数二:宽
        //参数三:颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0,0, width,height);

        //产生4个随机验证码,12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体",Font.BOLD,24));
        //向图片上写入验证码
        g.drawString(checkCode,15,25);

        //将内存中的图片输出到浏览器
        //参数一:图片对象
        //参数二:图片的格式,如PNG,JPG,GIF
        //参数三:图片输出到哪里去
        ImageIO.write(image,"PNG",response.getOutputStream());
    }
    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        int codelength = 4;
        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=codelength;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        System.out.println("验证码:" + sb);
        return sb.toString();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

用户登录LoginServlet

package main.com.web;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("进入LoginServlet代码文件!");

        //1.设置request编码
        req.setCharacterEncoding("utf-8");
        //2.获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verifycode = req.getParameter("verifycode");
        System.out.println(username);
        System.out.println(password);

        //3.先获取生成的验证码
        HttpSession session = req.getSession();
        String checkCode_session = (String) session.getAttribute("CHECKCODE_SERVER");
        //删除session中存储的验证码
        session.removeAttribute("CHECKCODE_SERVER");
        //3.先判断验证码是否正确
        if(checkCode_session!=null &&checkCode_session.equalsIgnoreCase(verifycode)){
            //忽略大小写比较
            //验证码正确
            //判断用户名和密码是否一致
            if("admin".equals(username) && "123456".equals(password)){//需要调用UserDao查询数据库
                //登录成功
                //存储信息,用户信息
                session.setAttribute("user",username);
                //重定向到success.jsp
                resp.sendRedirect(req.getContextPath()+"/success.jsp");
            }else{
                //登录失败
                //存储提示信息到request
                req.setAttribute("login_msg","用户名或密码错误");
                //转发到登录页面
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }

        }else{
            //验证码不一致
            //存储提示信息到request
            req.setAttribute("login_msg","验证码错误");
            //转发到登录页面
            resp.sendRedirect(req.getContextPath()+"/login.jsp");

        }
    }
}

index.jsp页面跳转


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>--%>



    
    
    
    文本信息管理系统

    
    
    
    
    
    
    


Hello World!

5秒后自动跳转到界面 <%--content后数字表示等待时间秒数--%>

Servlet + Session 验证码登录_第2张图片

跳转到登录界面

Servlet + Session 验证码登录_第3张图片

登陆

验证码失败、密码错误
Servlet + Session 验证码登录_第4张图片

你可能感兴趣的:(JavaWeb,java,web,servlet,session)