我有一个servlet在我的jsp页面上生成验证码,但很多时候我从这个servlet得到null并得到无效的验证码错误,我尝试了很多但仍然不知道为什么我在这里得到这个是我的验证码servlet
public class CaptchaServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int width = 200;
int height = 42;
char data[] = RandomStringUtils.randomNumeric(4).toLowerCase().toCharArray();
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
GradientPaint gp = new GradientPaint(0, 0,new Color(144, 46, 54), 0, height/2, new Color(144, 46, 54), true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.white);
Random r = new Random();
String captcha = String.copyValueOf(data);
System.out.println("In captcha Servlet :- "+captcha);
request.getSession().setAttribute("captcha", captcha );
int x = 0;
int y = 0;
for (int i=0; i<data.length; i++) {
x += 35 + (Math.abs(r.nextInt()) % 5);
y = 20 + Math.abs(r.nextInt()) % 5;
g2d.drawChars(data, i, 1, x, y);
}
g2d.dispose();
response.setContentType("image/png");
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", os);
byte[] bytes = os.toByteArray();
ServletOutputStream out = response.getOutputStream();
out.write(bytes);
os.close();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
下面是我的jsp代码
<div id="captcha_div">
<img id="captcha_img" src="<%=appContext%>/CaptchaServlet"
style="float: left; width: 70%; margin-top: 2%;">
<div style="padding-top: 5%; margin-left: 73%">
<button class="refresh" onclick="javascript:regenImage();"type="button">
</button></div></div>
我检查验证码和用户在另一个servlet中输入的代码,如
String code = request.getParameter("code");
String captcha = (String) session.getAttribute("captcha");
if (captcha != null && code != null) {
if (captcha.equals(code)) {
isValid = true;
}
}
我很少得到null,我重现的一种情况就像当登录页面保持理想的10,20分钟时我得到验证码的值是空的因为这个我得到无效的capcha错误你能告诉我为什么我得到null或我在代码中做错了谢谢...
答案 0 :(得分:0)
请将您的processRequest代码放在try catch中,并在提出请求时检查下面代码中的日志打印内容。
String captcha = String.copyValueOf(data);
System.out.println("In captcha Servlet :- "+captcha);
request.getSession().setAttribute("captcha", captcha );