验证码在春天不加载

时间:2019-05-27 18:12:13

标签: spring jsp captcha

我不知道为什么我的验证码没有加载到这个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中,它正在工作!

1 个答案:

答案 0 :(得分:0)

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

无论如何,通过将图像源更改为localhost:8080/captcha-image.png,一切正常!