JavaWeb项目------验证码(初级)
Servlet中的代码:
package com.tjk.session.cn;
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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Csession")
public class Csession extends HttpServlet {
private static final long serialVersionUID = 1L;
public Csession() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content", "image/jpeg");
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
BufferedImage image=new BufferedImage(50,30 , BufferedImage.TYPE_INT_BGR);
Graphics g=image.getGraphics();
g.setColor(Color.CYAN);
g.fillRect(0, 0, 50, 30);
g.setColor(Color.BLACK);
g.setFont(new Font(null,Font.BOLD,20));
String num=this.getCodeNum();
g.drawString(num, 0, 20);
request.getSession().setAttribute("code", num);
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public String getCodeNum(){
Random randow=new Random();
String num=randow.nextInt(9999)+"";
StringBuffer stringBuffer=new StringBuffer("");
for(int i=0;i<4-num.length();i++){
stringBuffer.append("0");
}
num+=stringBuffer;
return num;
}
}
显示界面上的代码(主要是图片的)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<img src="/Day10/Csession">
</body>
</html>