谢谢大家呀 2022-03-23 11:44 采纳率: 33.3%
浏览 58
已结题

Javaweb验证码检验

Javaweb编写代码完成登陆验证,在验证输入与给出验证码一致的第一个if条件报错,该怎么改

package chapter3.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 java.io.IOException;

@WebServlet(name = "LongingRedirectServlet",urlPatterns = "/LongingRedirectServlet")
public class LongingRedirectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String un=request.getParameter("username");
        String pw=request.getParameter("password");
        String verifycode=request.getParameter("verifycode");
        String yzm=(String)request.getSession().getAttribute("yzm");
        String a ="你好";

        if (verifycode.equals(yzm)) {     //**就是这里第一个条件怎么表述成输入输出一致?**
            if ("admin".equals(un)&&"123".equals(pw)) {
                getServletContext().setAttribute("username", un);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                response.sendRedirect(request.getContextPath()+"/chapter3/jsp/login_imagecode.jsp");
            }
        }else {
            a= "验证码错误请返重新输入";
        }


        if("admin".equals(un)&&"123".equals(pw)) {
            if (verifycode.equals(yzm)) {
                getServletContext().setAttribute("username", un);
                getServletContext().setAttribute("verifycode", verifycode);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }
        else {
            response.sendRedirect(request.getContextPath()+"/chapter3/jsp/login_imagecode.jsp");
        }
    }

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

还有这个index.jps需要怎么改


<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2022/2/22
  Time: 16:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>javaweb课程教学例程</title>
</head>
<body>
    <%
    String username=(String)application.getAttribute("username");
    String verifycode=(String)application.getAttribute("verifycode");
    if (username==null)
        username="";
    %>
<%=username%> 欢迎进入javaweb的世界!!
</body>
</html>

这是编写的login-imagecode.JSP


<%--
  Created by IntelliJ IDEA.
  User: 39519
  Date: 2022/3/1
  Time: 8:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript">
        // 切换验证码
        function refreshCode() {
            // 获取验证码图片对象
            var vcode = document.getElementById("vcode");
            // 设置src属性,加上时间戳
            vcode.src="${pageContext.request.contextPath}/imageCode?time=" + new Date().getTime();
        }
    </script>
</head>
<body>
<div class="container" style="width: 400px;">
    <h3 style="text-align: center;">验证码登录演示</h3>
    <form action="${pageContext.request.contextPath}/LongingRedirectServlet" method="post">
        <div class="form-group">
            <label for="user">用户名:</label>
            <input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
        </div>

        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
        </div>

        <div class="form-inline">
            <label for="vcode">验证码:</label>
            <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
            <a href="javascript:refreshCode()">
                <img src="${pageContext.request.contextPath}/imageCode" title="看不清点击刷新" id="vcode"/>
            </a>
        </div>
        <hr/>
        <div class="form-group" style="text-align: center;">
            <input class="btn btn btn-primary" type="submit" value="登录">
        </div>
    </form>
</div>
</body>
</html>


这是编写的验证码生成代码


package chapter01;

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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

@WebServlet(name = "CheckImageServlet",urlPatterns = "/imageCode")

public class CheckImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private List<String> words = new ArrayList<String>();// 集合中保存所有成语
    @Override
    public void init() throws ServletException {
        //读取文本文件中的成语存于集合类,并遍历输出,在控制台查看正确与否
        InputStream in = getServletContext().getResourceAsStream("/WEB-INF/words.txt");
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = bf.readLine()) != null) {
                words.add(line);//读取每一行的成语,并存于集合类words中
            }
            bf.close();
            Iterator<String> iter = words.iterator();
            while (iter.hasNext()) {
                String s = (String) iter.next();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 如下三句是控制浏览器禁止缓存当前文档内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
        int width = 180;
        int height = 30;
        // 步骤一 绘制一张内存中图片
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 步骤二 图片绘制背景颜色 ---通过绘图对象
        Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
        // 绘制任何图形之前 随机指定一个颜色
        graphics.setColor(getRandColor(200, 250));//在117行定义,随机取得颜色
        graphics.fillRect(0, 0, width, height);
        // 步骤三 绘制边框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);
        // 步骤四 四个随机数字,用到旋转等方法所以转换为Graphics2D
        Graphics2D graphics2d = (Graphics2D) graphics;
        // 设置输出字体
        graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
        Random random = new Random();// 生成随机数
        int index = random.nextInt(words.size());//在0和数组最大长度的范围内随机取一个下标
        String word = words.get(index-1);// 获得该下标对应的成语
        System.out.println(word);

        //对四字成语中的每个字设定颜色,旋转的角度
        // 定义x坐标
        int x = 10;
        for (int i = 0; i < word.length(); i++) {
            // 随机颜色
            graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            // 旋转 -30 --- 30度
            int jiaodu = random.nextInt(60) - 30;
            // 换算弧度
            double theta = jiaodu * Math.PI / 180;
            // 获得字母数字
            char c = word.charAt(i);
            // 将c 输出到图片
            graphics2d.rotate(theta, x, 20);
            graphics2d.drawString(String.valueOf(c), x, 20);
            graphics2d.rotate(-theta, x, 20);
            x += 40;
        }
        // 步骤五 绘制干扰线
        graphics.setColor(getRandColor(160, 200));
        int x1,x2,y1,y2;
        for (int i = 0; i < 30; i++) {
            x1 = random.nextInt(width);
            x2 = random.nextInt(12);
            y1 = random.nextInt(height);
            y2 = random.nextInt(12);
            graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
        }
        // 将上面图片输出到浏览器 ImageIO
        graphics.dispose();// 释放资源
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    /**
     * 取其某一范围的color
     * @param fc   int 范围参数1
     * @param bc   int 范围参数2
     * @return Color
     */
    private Color getRandColor(int fc, int bc) {
        // 取其随机颜色
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}

  • 写回答

4条回答 默认 最新

  • CSDN专家-sinJack 2022-03-23 11:55
    关注
    if (verifycode.equals(yzm))
    

    报错是空指针异常吧。verifycode这个变量为null,前端没有正确传值。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 3月31日
  • 已采纳回答 3月23日
  • 创建了问题 3月23日

悬赏问题

  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥20 unity内置语言切换的按钮设置
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器