Silly-M 2025-06-19 10:47 采纳率: 0%
浏览 5

IDEA环境无法生成验证码图片


package com.myt.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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/createImage")
public class CreateImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成验证码图片
        resp.setContentType("image/jpeg");
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
        resp.setDateHeader("Expires",0);


        //创建画布
        int width = 100;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics2D grah = (Graphics2D) image.getGraphics();
        grah.setColor(getRandColor(200,250));
        grah.fillRect(0,0,width,height);

        grah.setColor(getRandColor(160,200));

        Random r = new Random();


        //干扰线
        for (int i = 0; i < 20; i++) {
            int x = r.nextInt(width);
            int y = r.nextInt(height);
            int x1 = r.nextInt(12);
            int y1 = r.nextInt(12);
            grah.drawLine(x,y,x+x1,y+y1);

        }


        //画出验证码
        grah.setFont(new Font("Arial",Font.BOLD,24));
        StringBuilder StringBuilder = new StringBuilder();
        for(int i=0;i<4;i++){
            String code = String.valueOf(r.nextInt(10));
            StringBuilder.append(code);
            grah.setColor((getRandColor(20,130)));
            //字体
            grah.drawString(code,20*i+10,28);

        }

        //把正确的验证码值放在会话中
        HttpSession session = req.getSession();
        session.setAttribute("code",StringBuilder.toString());

        //释放图形对象
        grah.dispose();

        try {
            ImageIO.write(image, "JPEG", resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }



        //把图片放在response中
        ImageIO.write(image,"JPEG",resp.getOutputStream());
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
        resp.flushBuffer();


    }
    /**
     * 随机范围生成颜色对象
     * @return
     */
    private Color getRandColor(int min,int max){
        min = Math.min(min,255);
        max = Math.min(max,255);
        Random random = new Random();
        int r = min+random.nextInt(max-min);
        int g = min+random.nextInt(max-min);
        int b = min+random.nextInt(max-min);
        return new Color(r,g,b);
    }


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


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


<html>
<head>
    <meta charset="UTF-8">
    <title>教务管理系统</title>
    <%--加载了boostrap样式库--%>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css"/>
    <%--自定义的JS代码--%>
    <script type="text/javascript">
        function refresh() {
            //点击是应该再次请求,重新画一张图片
            var imgEle = document.getElementById("codeimage");//获取id获取图片标签对象
            imgEle.src = "${pageContext.request.contextPath}/createImage?" + new Date();//使用new Date()实现路径的刷新,预防缓存中图片重新加载
        }
    </script>
    <style type="text/css">

        body {
            background-image: url('${pageContext.request.contextPath}/image/bg1.jpg');
            background-size: cover;
        }

        .card {
            margin-top: 85px;
            background-color: rgba(0, 0, 0, 0.3);
        }
    </style>
</head>
<body>
<div class="container" align="center">

    <div class="card col-6 p-5 ">
        <h1>教务管理系统<sup>V1.0</sup></h1>
        <div class="bg-info text-white p-2 mt-2" align="center">
            <h4>用户登陆</h4>
        </div>
        <form class="form1" action="${pageContext.request.contextPath}/checkCode" method="post">
            <div class="input-group mt-3">
                <div class="input-group-prepend ">
                    <span class="input-group-text">用户名</span>
                </div>
                <input type="text" class="form-control" placeholder="请输入用户名" name="username" id="username"/>
            </div>
            <div class="input-group mt-3">
                <div class="input-group-prepend ">
                    <span class="input-group-text">密码</span>
                </div>
                <input type="password" class="form-control" placeholder="请输入密码" id="password" name="password"/>

            </div>
            <div class="input-group mt-3">
                <div class="input-group-prepend ">
                    <span class="input-group-text">请选择身份</span>
                </div>
                <select class="form-control" name="usertypes">
                    <option value="admin">管理员</option>
                    <option value="student">学生</option>
                </select>
            </div>
            <span style="font-size:15px;color:red; ">
                <%--page request session application--%>
                ${errorMsg}
            </span>

            <div class="input-group mt-3">
                <div class="input-group-prepend ">
                    <span class="input-group-text">验证码</span>
                </div>
                <input type="text" class="form-control" placeholder="请输入验证码" name="code"/>&nbsp;&nbsp;
                <img alt="验证码" src="${pageContext.request.contextPath}/createImage" onclick="refresh()" id="codeimage"
                     title="单击更换验证码"
                style="height: 40px;margin-left: 5px;cursor: pointer;">
            </div>
            <span class="errorcode" style="font-size:15px; color:red;">${codeMsg}</span>
            <br>
            <button type="submit" class="btn btn-success w-100 mt-3">登陆</button>
            <br/><br/>
            <a href="${pageContext.request.contextPath}/public/register.jsp" class="btn btn-primary btn-sm"
               role="button">没有账号?点击注册</a>
        </form>
    </div>

</div>
<script src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</body>
</html>


```

  • 写回答

5条回答 默认 最新

  • 阿里嘎多学长 2025-06-19 10:47
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    问题解答

    IDEA环境无法生成验证码图片可能是由于以下原因:

    1. IDEA 的 Maven 依赖项不正确或缺失。
    2. 项目的编译器版本不正确。
    3. 项目的 Java 版本不正确。

    解决方案:

    1. 检查 Maven 依赖项,确保添加了相关依赖项,例如 javax.imageio
    2. 检查项目的编译器版本,确保使用的是最新版本的 Java 编译器。
    3. 检查项目的 Java 版本,确保使用的是正确的 Java 版本。

    如果以上解决方案不生效,可以尝试以下命令:

    File -> Invalidate Caches / Restart -> Invalidate and Restart

    这将重新加载 IDEA 的缓存和重新启动 IDEA。

    如果问题仍然存在,可以提供更多的错误信息或项目配置信息,以便更好地帮助您解决问题。

    评论

报告相同问题?

问题事件

  • 创建了问题 6月19日