Session

Session:


Session实现原理:


浏览器未禁用Cookie:

Jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    <a href="/day07/servlet/SessionDemo1">购买</a>
    <a href="/day07/servlet/SessionDemo2">结账</a>
  </body>
</html>

Servlet代码:

//购买
public class SessionDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//第一次getSession时创建Session,默认30分钟没人用Session就自动摧毁了
		HttpSession session = request.getSession();
		//Session技术是基于Cookie技术实现的,每次创建完Session,都会将JSESSIONID写给浏览器
		//但是默认存放JSESSIONID的Cookie有效时间为0,即关闭浏览器Cookie就消失,所以默认情况下,一个浏览器独占一个Session
		//所以电子商务网站必须有以下过程,手动设置存放JSESSIONID的Cookie的有效时间和Session的一致
		//即重写存放JSESSIONID的Cookie,这样就实现了多浏览共享一个Session,即关闭浏览器再打开也能得到上次的Session
		String sessionid = session.getId();
		Cookie cookie = new Cookie("JSESSIONID",sessionid);
		cookie.setPath("/day07");
		cookie.setMaxAge(30*60);
		response.addCookie(cookie);
		session.setAttribute("name", "洗衣机");
		
		//不创建只获取,用于显示购物车,有人闲的不买直接结账查看购物车,这时不必创建session
//		request.getSession(false);
		
		
		//invalidate摧毁Session,或者在web.xml里<session-config>配置摧毁时间
//		session.invalidate();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

//结账
public class SessionDemo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-Type", "text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession(false);
		String product = (String)session.getAttribute("name");
		out.write("您购买的商品是:"+product);
		 
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
浏览器禁用Cookie:

Servlet代码:

//首页
public class WelcomeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//一访问首页自动创建Session,getSession首先检查cookie是否有JSESSIONID,再检查url后是否有JSESSIONID,如果都没有则新创建个Session
		request.getSession();
		
		//如果禁用了cookie,那么电子商务使用Session则需要重写url(但是这种方法却无法解决关闭浏览器再打开后,获取上一次Session)
		//让用户点击超链接自动带上JSESSIONID
		//以下两句实现了Url地址后自动加上JSESSIONID,Sun公司提供的方法
		//如果服务器发现用户没有禁用cookie,则不会重写url(第一次访问服务器既重写url又返回cookie,第二次访问,服务器发现有cookie,则url不会带参数)
		String url1 = response.encodeRedirectURL("/day07/servlet/SessionDemo1");
		String url2 = response.encodeRedirectURL("/day07/servlet/SessionDemo2");
		
		out.print("<a href='"+url1+"'>购买</a>    ");
		out.print("<a href='"+url2+"'>结账</a>");
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Session案例——实现简单的购物:

Servlet代码:

//商品类(书籍)
class Book{
	private String id;
	private String name;
	private String author;
	private String description;
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	
}

//数据库(如果有检索数据需求,则用双列(Map),如果不检索,则用单列(List)	)
class Db{
	private static Map<String,Book> map = new LinkedHashMap();  //如果用HashMap,则获取商品顺序和存入顺序不一致,hashMap是根据hash值排列的
	//静态块,一使用Db类就自动执行
	static{
		map.put("1", new Book("1","javaweb开发","老张","一本好书"));
		map.put("2", new Book("2","jdbc开发","老张","一本好书"));
		map.put("3", new Book("3","spring开发","老黎","一本好书"));
		map.put("4", new Book("4","struts开发","老毕","一本好书"));
		map.put("5", new Book("5","android开发","老黎","一本好书"));
	}
	
	public static Map getAll(){
		return map;
	}
}
//代表网站首页,列出所有书
public class ListBookServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//以后学习过滤器filter,设置一次,则所有资源都解决中文乱码,不必每次都设置
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		request.getSession();//一访问首页就建立session,以防cookie禁用,则用重写url
		
		out.print("本网站有如下商品:<br/>");
		Map<String,Book> map = Db.getAll();
		for(Map.Entry<String, Book> entry : map.entrySet()){
			Book book = (Book)entry.getValue();
			String url = response.encodeRedirectURL(request.getContextPath()+"/servlet/BuyServlet?id="+book.getId());
			out.print(book.getName()+" <a href='"+url+"' target='_blank'>购买</a><br/>");
		}
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
//完成购买
public class BuyServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String id = request.getParameter("id");
		Book book = (Book)Db.getAll().get(id);
		
		HttpSession session = request.getSession(false);
		//手工以cookie形式发sessionid,来解决关闭浏览器后,上次买的东西还在
		String sessionid = session.getId();
		Cookie cookie = new Cookie("JSESSIONID",sessionid);
		cookie.setMaxAge(30*60);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		
		//从Session中得到用户用于保存所有书的集合(得到用户的购物车)
		List list = (List)session.getAttribute("list");
		if(list==null){
			list = new ArrayList();
			session.setAttribute("list", list);
		}
		list.add(book);
		
		//到结账界面要用重定向
		response.setStatus(302);
		//最好不写死跳转路径,用request.getContextPath()得到当前web应用目录
		String url = response.encodeRedirectURL(request.getContextPath()+"/servlet/ListCartServlet");
		response.setHeader("Location", url);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

//显示用户购买的商品
public class ListCartServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession(false);
		if(session==null){
			out.print("您没有购买任何商品!!");
			return;
		}
		
		out.print("您购买了如下商品:<br/>");
		List<Book> list = (List)session.getAttribute("list");
		for(Book book : list){
			out.print(book.getName()+"<br/>");
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Session案例——完成用户的登录:
html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>login.html</title>
  </head>
  
  <body>
    <form action="/day07/servlet/LoginServlet" method="post">
    	用户名:<input type="text" name="username"/><br/>
    	密码:<input type="password" name="password"/><br/> 
    	<input type="submit" value="登录"/>    
    </form>
  </body>
</html>

Servlet代码:

//用户类
public class User {
	private String username;
	private String password;
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}
//数据库
class DB{
	public static List list = new ArrayList();
	static{
		list.add(new User("aaa","123"));
		list.add(new User("bbb","123"));
		list.add(new User("ccc","123"));
	}
	public static List getAll(){
		return list;
	}
}
//完成用户登录
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		List<User> list = DB.getAll();
		for(User user : list){
			if(user.getUsername().equals(username)&&user.getPassword().equals(password)){
				request.getSession().setAttribute("user", user);	//登录成功,向Session存入一个登录标记
				response.setStatus(302);
				response.setHeader("Location", "/day07/index.jsp");
				return;
			}
		}
		
		out.write("用户名或密码不对!!");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
//完成用户注销
public class LogoutServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession(false);
		if(session==null){
			response.setStatus(302);
			response.setHeader("Location", "/day07/index.jsp");
			return;
		}
		
		session.removeAttribute("user");
		response.setStatus(302);
		response.setHeader("Location", "/day07/index.jsp");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  	
  <body>
  	欢迎您:${user.username} <a href="/day07/login.html">登录</a> <a href="/day07/servlet/LogoutServlet">退出登录</a>
  	<br/><br/><br/>
    <a href="/day07/servlet/SessionDemo1">购买</a>
    <a href="/day07/servlet/SessionDemo2">结账</a>
  </body>
</html>

Session案例——防止表单重复提交:
客户端javascript防止表单重复提交:


html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>form.html</title>
    <!-- 用js阻止表单重复提交(属于客户端阻止重复提交,不安全,用户可以自己重写提交页面或者刷新/后退页面继续提交) 
    	但是还是要用客户端阻止一下,再用服务器阻止-->
    <script type="text/javascript">
    	/*
    	var iscommitted = false;
    	function dosubmit(){
    		if(!iscommitted){
    			iscommitted=true;
    			return true;
    		}
    		else{
    			return false;
    		}
    	}
    	*/
    	function dosubmit(){
    		var input = document.getElementById("submit");
    		input.disabled = 'disabled';
    		return true;
    	}
    </script>
  </head>
  
  <body>
    <form action="/day07/servlet/DoFormServlet" method="post" onsubmit="return dosubmit()">
    	用户名:<input type="text" name="username"/>
    	<input id="submit" type="submit" value="提交" />
    </form>
  </body>
</html>

服务器端session防止表单重复提交:

Servlet代码:

//令牌发生器,为了保证发生的令牌唯一性(低重复概率),要设计成单类
class TokenProcessor{	
	/** 单类设计方法:
	 * 1.把构造方法私有
	 * 2.自己创建一个实例
	 * 3.对外暴露一个方法,允许获取上面创建的对象
	 */
	private TokenProcessor(){}
	private static final TokenProcessor instance = new TokenProcessor();
		
	public static TokenProcessor getInstance(){
		return instance;
	}
	//产生令牌(随机数)的方法
	public String generateToken(){
		
		//为了随机数尽可能唯一,令牌里用 当前毫秒值+随机数
		String token = System.currentTimeMillis() + new Random().nextInt() + "";
		
		try {
			//为了保证随机数长度固定,需要得到数据指纹(即数据摘要,只有128位(bit),即16字节(byte))
			MessageDigest md = MessageDigest.getInstance("md5");//用md5算法算出数据摘要
			byte[] md5 = md.digest(token.getBytes());//得到数据摘要,数组长度始终未16
			
			//base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} 
		catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
}
//产生表单
public class FormServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//产生一个随机数(表单号)
		TokenProcessor tp = TokenProcessor.getInstance();
		String token = tp.generateToken();
		
		//服务器保存一份表单号(token)
		request.getSession().setAttribute("token", token);
		
		//转发到表单页面
		request.getRequestDispatcher("/form.jsp").forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'form.jsp' starting page</title>
  </head>
  
  <body>
    <form action="/day07/servlet/DoFormServlet" method="post">
    	<input type="hidden" name="token" value="${token }"/>
    	用户名:<input type="text" name="username"/><br/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>

Servlet代码:

//处理表单
public class DoFormServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		boolean b = isTokenValid(request);
		if(!b){
			System.out.println("请不要重复提交!");
			return;
		}
		
		request.getSession().removeAttribute("token");
		System.out.println("处理:向数据库注册用户~~~~");
		
	}

	//判断表单号是否有效
	private boolean isTokenValid(HttpServletRequest request) {
		
		//得到客户端提交表单时带的token(表单号)
		String client_token = request.getParameter("token");
		if(client_token==null){ //客户端未通过程序输出的表单提交,则不带token
			return false;
		}
		//得到服务器端session中存放的token(表单号)
		String server_token = (String)request.getSession().getAttribute("token");
		if(server_token==null){ //服务器端没有token,表示已经提交过了
			return false;
		}
		if(!client_token.equals(server_token)){ //客户端带来的token和服务器端token不一致
			return false;
		}
		
		return true;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Session案例——校验图片认证码:


Servlet代码:

//输出一张随机图片   
public class ImageServlet extends HttpServlet {  
  
    public static final int WIDTH = 120;  
    public static final int HEIGHT = 35;  
      
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
          
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);  
          
        Graphics g = image.getGraphics();  
          
        //1.设置背景色   
        setBackground(g);  
          
        //2.设置边框   
        setBorder(g);  
          
        //3.画干扰线   
        drawRandomLine(g);  
          
        //4.写随机数   
        String random = drawRandomNum((Graphics2D)g);  
        request.getSession().setAttribute("checkcode", random);
          
        //5.图形写给浏览器   
        response.setHeader("Content-Type", "image/jpeg");  
        //发头控制浏览器不要缓存   
        response.setDateHeader("expries", -1);  
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "no-cache");  
          
        ImageIO.write(image,"jpg",response.getOutputStream());  
          
    }  
      
    private void setBackground(Graphics g){  
        g.setColor(Color.WHITE);  
        g.fillRect(0, 0, WIDTH, HEIGHT);  
    }  
      
    private void setBorder(Graphics g){  
        g.setColor(Color.BLUE);  
        g.drawRect(1, 1, WIDTH-2, HEIGHT-2);  
    }  
      
    private void drawRandomLine(Graphics g){  
        g.setColor(Color.GREEN);  
        for(int i = 0 ;i < 5; i++){  
            int x1 = new Random().nextInt(WIDTH);  
            int y1 = new Random().nextInt(HEIGHT);  
              
            int x2 = new Random().nextInt(WIDTH);  
            int y2 = new Random().nextInt(HEIGHT);  
              
            g.drawLine(x1, y1, x2, y2);  
        }  
    }  
      
    private String drawRandomNum(Graphics2D g){  
          
        g.setColor(Color.RED);  
        g.setFont(new Font("宋体",Font.BOLD,20));  
          
        StringBuffer sb = new StringBuffer();
        //[\u4e00-\u9fa5] 表示:所有的汉字在unicode编码4e00~9fa5之间   
        //常用汉字的unicode编码   
        String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";  
        int x = 5;  //第一个字的x坐标   
        for(int i = 0;i<4;i++){  
            int degree = new Random().nextInt()%30;//-30~30   
            String ch = base.charAt(new Random().nextInt(base.length()))+"";
            sb.append(ch);  
            g.rotate(degree*Math.PI/180, x, 20);//设置旋转角度   
            g.drawString(ch, x, 20);  
            g.rotate(-degree*Math.PI/180, x, 20);  
            x = x + 30;  
        }  
        return sb.toString();
    }  
      
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
  
}

html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <title>register.html</title>  
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> 
    
    <script type="text/javascript">  
        function changeImage(img){  
            img.src = img.src + "?" + new Date().getTime();  
        }  
    </script>  
      
  </head>  
    
  <body>  
    <form action="/day07/servlet/RegisterServlet" method="post">  
        用户名:<input type="text" name="username"/><br/>  
        密码:<input type="password" name="password"/><br/>  
        认证码:<input type="text" name="checkcode"/>  
        <img src="/day07/servlet/ImageServlet" onclick="changeImage(this)" title="换一张" style="cursor:hand"/><br/>  
        <input type="submit" value="注册"/>  
    </form>  
  </body>  
</html>  

Servlet代码:

//处理注册请求
public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//认证码是汉字,所以要设置一下request编码
		request.setCharacterEncoding("UTF-8");
		
		//处理注册请求之前,检验认证码是否有效
		String client_checkcode = request.getParameter("checkcode");
		String server_checkcode = (String)request.getSession().getAttribute("checkcode");
		if(client_checkcode!=null&&server_checkcode!=null&&client_checkcode.equals(server_checkcode)){
			System.out.println("client_checkcode = " + client_checkcode);
			System.out.println("server_checkcode = " + server_checkcode);
			System.out.println("处理注册请求!");
		}
		else{
			System.out.println("client_checkcode = " + client_checkcode);
			System.out.println("server_checkcode = " + server_checkcode);
			System.out.println("认证码错误!");
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


 

posted @ 2013-04-24 21:11  魅惑之眼  阅读(272)  评论(0编辑  收藏  举报