使用response输出随机验证码图片。
Posted 离落想AC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用response输出随机验证码图片。相关的知识,希望对你有一定的参考价值。
使用response输出随机验证码图片。
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ResponsegetVerificationCode
*/
public class ResponsegetVerificationCode extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ResponsegetVerificationCode() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
getVerificationCode(request,response);
}
/**
* @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);
}
private void getVerificationCode(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
int width = 120;
int height = 25;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.BLUE);
g.drawRect(0, 0, width, height);
g.setColor(Color.YELLOW);
g.fillRect(1, 1, width-2, height-2);
g.setColor(Color.GRAY);
Random r = new Random();
for(int i=0;i<10;i++)
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 20));
int x = 23;
for(int i=0;i<4;i++){
g.drawString(r.nextInt(10)+"", x, 20);
x+=20;
}
ImageIO.write(image, "jpg", response.getOutputStream());
}
}
浏览器访问: http://localhost:8888/MyJspProject/ResponsegetVerificationCode
Eclipse运行:
以上是关于使用response输出随机验证码图片。的主要内容,如果未能解决你的问题,请参考以下文章