您的位置:首页 > 其它

【Servlet】实现简单的验证码生成与验证

2015-09-19 09:02 519 查看
简单的四位数字验证码生成,带看不清刷新验证密码的功能

登陆界面:

验证码:<input type="text" name="loginCode" id="loginCode" />

<img src="code.do" id="codeImage" style="width:80px;height:20px">

<input type="button" id = "getCode" value="看不清" onclick="button_onclick()" />

<br/>

//设置了图片大小,添加了刷新图片的button

JavaScript:

<script type="text/javascript">

function button_onclick(){

var src = "code.do/" + Math.random();

document.getElementById("codeImage").src = src;

}

</script>

//实现图片刷新功能,通过添加随机数生成不同的请求

web.xml:servlet-mapping这样设置

<servlet-mapping>

<servlet-name>code</servlet-name>

<url-pattern>/code.do/*</url-pattern>

</servlet-mapping>

生成验证码的Servlet:

public class Code extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("image/jpeg");

BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

g.setColor(Color.BLACK);

int h = 20;

int w = 80;

g.fillRect(0, 0, w, h);

g.setColor(Color.BLUE);

g.drawRect(1, 1, 78, 18);

String code = "";

Random r = new Random();

for(int i = 0; i < 4; i++){

int a = r.nextInt(9);

code += a;

}

HttpSession hs = request.getSession();

hs.setAttribute("code", code);//将随机生成的4位验证码存入会话

g.setColor(RandomColor.randomColor());

g.drawString(code, 25, 15);

//随机十条线

for(int i = 0; i < 10; i++){

int x = r.nextInt(w);

int y = r.nextInt(h);

int x1 = r.nextInt(12);

int y1 = r.nextInt(12);

g.setColor(RandomColor.randomColor());

g.drawLine(x, y, x + x1, y + y1);

}

//设置网页立刻过期

response.setDateHeader( "expries" , -1 );

response.setHeader("cache-control" , "no-cache");

response.setHeader("Pragma" , "no-cache");

//将image写给浏览器

ImageIO.write( image , "jpg" , response.getOutputStream() );

}

}

生成随机颜色的辅助类:

public class RandomColor {

public static Color randomColor(){

int r = 0;

int b = 0;

int g = 0;

Random random = new Random();

r = random.nextInt(255);

g = random.nextInt(255);

b = random.nextInt(255);

Color c = new Color(r,g,b);

return c;

}

}

进行验证的Servlet:

String code = request.getParameter("loginCode");//取JSP中的 code

code.equals(request.getSession().getAttribute("code"))//与session中的code比较
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: