Servlet3.0 验证码

package com.lee;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//Servlet 3.0的 Annoation

/*			@WebServlet 支持的常用属性
asyncSupported    否               指定该 Servlet 是否支持异步操作模式 .
displayname       否		  指定 该servlet 的显示名称
initparams		      否              为该servlet 配置参数
loadOnStartup	     否		 将该serlvet 配置成 load-on-startup类型的servlet
name              否	 	指定 该servlet的名称
urlPatterns/ value 否           这两个属性 的作用完全相同,都指定该Servlet 的 处理 URL

如果使用 Annotation 
   1:不需要在 web.xml 根元素 <web-app>中加入  metadata-complete="true".
   2:不要在web.xml中配置该serlvet 
   
Servlet 中的 不写 doGet 或者 doPost  可以统一交给 serlvet中  service方法处理.
*/
@WebServlet(name="ImageServlet",urlPatterns={"/ImageServlet"})
public class ImageServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		int width=80;
		int height=30;
		
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g=image.createGraphics();
	
		//画背景  选取颜色,然后画大小
		g.setColor(getRandColor(240,255));  //偏淡色
		g.fillRect(0, 0, width, height);
		
		//画边框
		g.setColor(getRandColor(200,255));  
		g.fillRect(0, 0, width-1, height-1);
		
		//画 干扰线 8条
		g.setColor(getRandColor(100,255));  
		Random random=new Random();
		
		for(int i=0;i<8;i++){  //两点确定一条直线,
			int x1=random.nextInt(width);
			int y1=random.nextInt(height);
			
			int x2=random.nextInt(width);
			int y2=random.nextInt(height);
			
			g.drawLine(x1, y1, x2, y2);
		}
		
		//画 干扰 点
		for(int i = 0;i<50;i++) 
		{ 
			int x = random.nextInt(width); 
			int y = random.nextInt(height); 
			g.setColor(new Color(x+100,y+100,100)); 
			g.drawOval(x, y, 1, 0); 
		} 
		Font font=new Font("Times New Roman",Font.ITALIC,24);
		g.setFont(font);
		
		int length=4;
		int x = width / length;  //字体间隔宽度
		int codeY = height-font.getSize();  // 字体 高度
	
		String s="qwertyuiopl0123456987kjhgfdsazxcvbnm0123456987QWERTYUIOPLKJH0123456987GFDSAZXCVBNM";
		String code="";
		for(int i=0;i<length;i++){
			g.setColor(new Color(85+random.nextInt(110),85+random.nextInt(110),85+random.nextInt(110)));
			String ch=String.valueOf(s.charAt(random.nextInt(s.length())));
			code+=ch;
			g.drawString(ch, i*x+5, font.getSize()+random.nextInt(codeY));
		}
		System.out.println(code);
		//存储字符串到 session中
		HttpSession session =req.getSession();
		session.setAttribute("checkcode", code);
		g.dispose();
		
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "No-cache");
		resp.setDateHeader("Expires", 0);
		resp.setContentType("image/jpeg");
		
		//输出到流中
		ServletOutputStream out=resp.getOutputStream();
		ImageIO.write(image, "jpeg",out);
		out.flush();
		out.close();
		
	}
	

	public Color getRandColor(int lower,int upper){ 
	  Random random = new Random(); 
	  if(upper>255) 
	   upper=255; 
	  if(upper<1) 
	   upper=1; 
	  if(lower<1) 
	   lower=1; 
	  if(lower>255) 
	   lower=255; 
	  int r=lower+random.nextInt(upper-lower); 
	  int g=lower+random.nextInt(upper-lower); 
	  int b=lower+random.nextInt(upper-lower); 
	  return new Color(r,g,b); 
	} 
	
}



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="system/error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%!
public int mcount;

%>

<script type="text/javascript" language="javascript"> 
  function changeImg(){ 
  	 var a=document.getElementById("mySpan"); 
  	  a.innerHTML='<img align="middle" src="ImageServlet"/>  <a href="#" onclick="changeImg();">看不清</a>'; 
  } 
</script> 
<body>
<%-- <%@ include file="system/include.jsp"%> --%>
<jsp:include page="system/include.jsp"/>
使用 子页面中变量<br/>
<%
response.sendRedirect("anyScope.jsp");
%>
<span id="mySpan"><img align="middle" src="ImageServlet" />
<a href="#" onclick="changeImg();">看不清</a></span> 
</body>
</html>

你可能感兴趣的:(servlet,验证码)