pageEncoding="GBK"%>
<%@ page import="java.awt.*" %>
<%@ page import="java.awt.image.*" %>
<%@ page import="java.util.*" %>
<%@ page import="javax.imageio.*" %>
<%!
Color getRandColor(int fc,int bc){
Random r = new Random();
if(fc > 255)
fc = 255;
if(bc > 255)
bc = 255;
int red = fc + r.nextInt(bc - fc);
int green = fc + r.nextInt(bc - fc);
int blue = fc + r.nextInt(bc - fc);
return new Color(red,green,blue);
}
%>
<%
//設置頁面不緩存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//下面開始了--生成圖像
Random r = new Random();
int width = 60,height = 20;
BufferedImage pic = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics gc = pic.getGraphics();
gc.setColor(getRandColor(200,250));
gc.fillRect(0, 0, width, height);
gc.setFont(new Font("Times New Roman",Font.PLAIN,18));
gc.setColor(getRandColor(160,200));
for(int i=0;i<200;i++){
int x1 = r.nextInt(width);
int y1 = r.nextInt(height);
int x2 = r.nextInt(15);
int y2 = r.nextInt(15);
gc.drawLine(x1, y1, x2, y2);
}
gc.setColor(getRandColor(120,240));
for(int i=0;i<100;i++){
int x = r.nextInt(width);
int y = r.nextInt(height);
gc.drawOval(x, y, 0,0);
}
String rs="";
String rn="";
for(int i = 0;i<4;i++){
rn = String.valueOf(r.nextInt(10));
rs += rn;
gc.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
gc.drawString(rn,13*i+6,16);
}
gc.dispose();
try{
session.setAttribute("code", rs);//設置session的屬性code為生成的驗證碼(String類型),JSP中壹般靠session等來傳遞並獲得參數
}catch(Throwable t){
getServletContext().log(t.getMessage());//這裏是寫log,但要抓異常
}
ImageIO.write(pic,"JPEG",response.getOutputStream());//輸出圖片到壹頁面,就是流
out.clear();//後面壹定要關閉流,因為在其他頁面會有沖突
out = pageContext.popBody();
%>
上面時code.jsp
另壹頁面只寫壹句話就能看到圖片:
<img src="code.jsp">
因為code.jsp可以向某個jsp頁面輸送壹個圖片,當然是驗證碼圖片~