java生成验证码

2019-04-15 16:50发布

data/attach/1904/9rrktqkyqbqumur2jzptf8o4v1c7qj4x.jpgdata/attach/1904/xmbc00t2old7vusrhso26fktd7mr5jiw.jpg 1,jsp页面<%String path=request.getContextPath();%> 
 生成验证码:验证码看不清
 
 
2,生成验证码代码  package com.spring.ImageServlet;
import java.awt.Color;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;
import javax.imageio.ImageIO;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ BufferedImage bi=new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB); Graphics g=bi.getGraphics(); Color c = new Color(new java.util.Random(30).nextInt(10),new java.util.Random(70).nextInt(10),new                                                                  java.util.Random(110).nextInt(10)); g.fillRect(1, 1, 65, 28); char[] ch ="ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray(); Random r = new Random(); StringBuffer sb = new StringBuffer(); int len =ch.length,index; 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]); } request.getSession().setAttribute("picCode", sb.toString()); ImageIO.write(bi, "JPG", response.getOutputStream()); }}
3,验证码验证代码package com.spring.ImageServlet;
import java.io.IOException;import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ request.setCharacterEncoding("UTF-8"); String picCode = (String) request.getSession().getAttribute("picCode"); String checkcode = request.getParameter("checkcode"); response.setContentType("text/html;charset=utf-8");    PrintWriter out = response.getWriter(); if(picCode.equals(checkcode)){ out.print("正确,哈哈哈"); } else{ out.println("笨蛋错了"); } out.flush(); out.close(); } }
4,web配置页面  Checkcode      index.html    index.htm    index.jsp    default.html    default.htm    default.jsp        ImageServlet  com.spring.ImageServlet.ImageServlet         LoginServlet  com.spring.ImageServlet.LoginServlet        ImageServlet  /servlet/ImageServlet          LoginServlet  /servlet/LoginServlet