package com.oracle.mvc;
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;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/validateCode")
public class ValidateCodeServelet extends HttpServlet{
//驗證碼 GDI+技術 PHP NET JAVA 繪圖技術 點 線 面 圖檔
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//jsp-api jar包
//jsp的九大内置對象
//request response session application out Exception config page pageContext
//作用域 pageContext request session application
//servelt-api jar包
//Servlet的5大對象
//HttpServletRequest HttpServletResponse HttpSession ServletContext HttpCookie
//request.getParamter(""); //擷取前台的參數
//response.sendRedirect("");//重定向 不帶資料
//req.getRequestDispatcher().forward();//轉發 //帶資料
//req.getSession();
HttpSession session=req.getSession();
Random random=new Random();
int width=100;
int height=52;
//1、準備好一張圖檔 矩形
BufferedImage validateCodeIMG=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2、擷取圖檔的畫筆
Graphics graphics = validateCodeIMG.getGraphics();
graphics.setColor(Color.WHITE);
//3、繪制矩形
graphics.fillRect(0,0,width,height);
//4、準備素材 0-9+A-Z+a-z
String[] res = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","j","m","n","q","r","t","v","x","y","A","B","C","D","E","F","G","H","I","J","M","N","Q","R","T","X","Y","中","大","國","華","人","名","共","你","張","三"};
Font font=new Font("微軟雅黑",Font.BOLD,25);
graphics.setFont(font);
//5、開始繪制4個 随機
String data="";
for (int i=0;i<4;i++){
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int index = random.nextInt(res.length);
String num=res[index];
data+=num;
graphics.drawString(num,i*20,30);
}
session.setAttribute("validateCode",data);
//6、繪制幹擾線
for (int i=0;i<10;i++){
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int ox=random.nextInt(width);
int oy=random.nextInt(height);
int ox2=random.nextInt(width);
int oy2=random.nextInt(height);
graphics.drawLine(ox,oy,ox2,oy2);
}
//7、繪制幹擾點
for (int i=0;i<10;i++){
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int ox=random.nextInt(width);
int oy=random.nextInt(height);
graphics.fillOval(ox,oy,5,5);
}
//8、渲染到圖檔 圖檔格式 png jpeg
ImageIO.write(validateCodeIMG,"jpeg",resp.getOutputStream());
}
}