为了账号安全,请及时绑定邮箱和手机立即绑定

验证码图片不显示,代码如下,求大神解答谢谢

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function reloadCode() {
 var time=new Date().getTime();
 document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+time;
}
</script>
</head>
<body>
<form action="<%=request.getContextPath()%>/servlet/LoginServlet" method="get">
验证码:<input type="text" name="checkcode"/>
<img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/servlet/ImageServlet"/>
<a href="javascript:reloadCode();">看不清楚</a><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>

ImageServlet.java

package code;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ImageServlet extends HttpServlet {


 protected void doGet(HttpServletRequest request, HttpServletResponse response){
  BufferedImage bi=new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
  Graphics g=bi.getGraphics();
  Color c=new Color(200,150,225);
  g.setColor(c);
  g.fillRect(0, 0, 68, 22);
  char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
  Random r=new Random();
  int len=ch.length,index;
  StringBuffer sb=new StringBuffer();
  for(int i=0;i<4;i++) {
   index=r.nextInt(len);
   g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
   g.drawString(ch[index]+"",(i*15)+3, 18);
   sb.append(ch[index]);
  }
 }

}

web.xml

<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>code.ImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/servlet/ImageServlet</url-pattern>
  </servlet-mapping>


正在回答

1 回答

ImageServlet.java中最后缺少request.getSession().setAttribute("piccode", sb.toString());
  ImageIO.write(bi, "JPG", response.getOutputStream());加上也没能显示

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Java实现验证码制作
  • 参与学习       59909    人
  • 解答问题       128    个

本教程就会带大家学习使用java实现各种验证码的方法

进入课程

验证码图片不显示,代码如下,求大神解答谢谢

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信