📄 validatecode.java
字号:
package com.fendou.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ValidateCode extends HttpServlet {
private int width=60;
private int height=20;
private static Random rand=new Random();
public ValidateCode() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage buffer=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics2D g=buffer.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width-1, height-1);
g.setColor(Color.GRAY);
for(int i=0;i<160;i++){
int x=rand.nextInt(width);
int y=rand.nextInt(height);
int x1=rand.nextInt(12);
int y1=rand.nextInt(12);
g.drawLine(x, y, x+x1, y+y1);
}
StringBuffer randCode=new StringBuffer();
Font font=new Font("Times New Roman",Font.BOLD,16);
for(int i=0;i<4;i++){
String str=String.valueOf(this.getChar());
g.setColor(new Color(rand.nextInt(110),rand.nextInt(50),rand.nextInt(50)));
g.setFont(font);
g.drawString(str, 13*i+6, 16);
randCode.append(str);
}
HttpSession session=request.getSession();
session.setAttribute("validCode", randCode.toString());
response.setHeader("Cache-Contorl", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream out=response.getOutputStream();
ImageIO.write(buffer,"jpeg",out);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
}
public char getChar(){
return (char)(65+rand.nextInt(26));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -