验证码未加载 spring

captcha does not load in spring

我不知道为什么我的验证码没有加载到这个 jsp 页面!在我的其他 jsp 页面上效果很好。我通过一个servlet做到了。像这样:

public class CaptchaServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedImage buffer =new BufferedImage(140, 50, BufferedImage.TYPE_INT_RGB);
        Graphics g = buffer.createGraphics();
        g.fillRect(1,1,138,48);
        Random rr = new Random();
        int x,y,r;
        g.setColor(Color.black);
        for(int i=0;i<119;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            r = 1+rr.nextInt(3);
            g.fillOval(x,y,r,r);
        }
        String str = "";
        String s = "";
        int n = 4 + rr.nextInt(3);
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m;
        boolean found = false;
        for(int i=0;i<n;i++) {
            m = p.matcher(s);
            while (!m.find()) {
                r = 65 + rr.nextInt(63);
                s = s.format("%c", r);
                m = p.matcher(s);
            }
            str = str + s;
            s = "";
        }

        HttpSession session = request.getSession();
        session.setAttribute( "captcha", str );

        //TimesRoman Font.PLAIN SansSerif
        g.setFont(new Font("SansSerif", Font.BOLD, 22));
        for(int i=0;i<str.length();i++) {
            s = str.substring(i,i+1);
            x = 4+20*i+rr.nextInt(5);
            y = 20+rr.nextInt(20);
            g.drawString(s, x, y);
        }
        g.setXORMode(Color.white);
        for(int i=0;i<199;i++) {
            x = 2+rr.nextInt(136);
            y = 2+rr.nextInt(46);
            g.drawLine(x,y,x,y);
        }
        response.setHeader("Cache-Control", "no-store"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache");        //HTTP 1.0
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(buffer, "png", os);
        os.flush();
        os.close();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

这是我的 jsp 验证码被调用的地方:

 <tr>
      <td><br/><img src="captcha-image.png"></td>
      <td style="margin-right: 5px;" valign="top"><br/>&nbsp;&nbsp;Enter code
      <br><input type="text" name="captcha_text" value="" style="margin-left: 5px;"></td>
 </tr>

当我在上面按 ctrl+b 时,它会正确地转到 servlet 映射。但为什么它没有加载?在另一个 jsp 它正在工作!

我找到了!当我查看页面源时,图像源指向 localhost:8080/votePoll/{id}/captcha-image.png 而不是它应该指向的 localhost:8080/captcha-image.png 。我不知道为什么会这样,因为在我的另一个 jsp 中并非如此。

无论如何,将图像源更改为 localhost:8080/captcha-image.png 效果很好!