制作一个简单的验证码

//验证码

/**
* Servlet implementation class RandomCodeServlet
*/
@WebServlet("/RandomCodeServlet")
public class RandomCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public RandomCodeServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

int width=130;
int height=53;
// 设置响应样式为。。。。类型
response.setContentType("image/jpeg");
BufferedImage bufimg =new BufferedImage(width,height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D) bufimg.getGraphics();
Color c=new Color((int) (Math.random()*35)+219,(int)
(Math.random()*35) +219, (int) (Math.random()*35)+219);

g.setBackground(c);

g.clearRect(0, 0, width, height);
// 产生随机的颜色分量来够着颜色值输出字符颜色值符都不同
Color fc=new Color((int) (Math.random()*71)+55,(int)
(Math.random()*71) +55, (int) (Math.random()*71)+55);
g.setColor(fc);
// 设置字体字体的大小和图片高度相关
g.setFont(new Font("Times New Roman", Font.BOLD, 35));
// 画边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);

// randomCode 用于保存随机产生的验证码以便用户登录后进行验证
StringBuffer randomCode=new StringBuffer();
// 随机产生的文字输出Y坐标的位置

int sp= (int)(Math.random()*30)+22;
// 随机产出四位数的验证码
for (int i = 0; i<4; i++) {
// 得到随机产生的字符
char strRand =(char)(Math.random()>0.50 ?
(int)(Math.random()*25) +65:(int) (Math.random()*25)+97 );
// 用随机产生的颜色将验吗绘制到图像中
g.drawString(String.valueOf(strRand), 24*i+12,
sp+(int)(Math.random()*5));

// j将四个合在一起
randomCode.append(strRand);
}
g.drawLine(0, sp-(int) (Math.random()*20), 130,
sp-(int)(Math.random()*20));

// 将图像输出到Srvlet流中
ServletOutputStream sos =response.getOutputStream();
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(sos);
encoder.encode(bufimg);

}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

posted @ 2016-08-23 23:17  瞄思玲  阅读(183)  评论(0编辑  收藏  举报