JavaWeb -- Session实例 -- 自动登录 和 防止表单重复提交(令牌产生器) MD5码

1、 自动登录

http://blog.csdn.net/xj626852095/article/details/16825659


2. 防止表单重复提交

表单Servlet 

//负责产生表单
public class FormServlet extends HttpServlet {

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

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String token = TokenProccessor.getInstance().makeToken();
		request.getSession().setAttribute("token", token);  //在服务器端保存随机数
		
		out.println("<form action='/day07/servlet/DoFormServlet' method='post'>");
			out.write("<input type='hidden' name='token' value='"+token+"'>");
			out.println("用户名:<input type='text' name='username'>");
			out.println("<input type='submit' value='提交'>");
		out.println("</form>");
	}

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

		doGet(request, response);
	}
}

class TokenProccessor{
	
	/*
	 *单态设计模式(保证类的对象在内存中只有一个)
	 *1、把类的构造函数私有
	 *2、自己创建一个类的对象
	 *3、对外提供一个公共的方法,返回类的对象
	 * 
	 */
	private TokenProccessor(){}
	
	private static final TokenProccessor instance = new TokenProccessor();
	
	public static TokenProccessor getInstance(){
		return instance;
	}
	
	
	public String makeToken(){  //checkException
		
		//  7346734837483  834u938493493849384  43434384
		String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
		
		//数据指纹   128位长   16个字节  md5
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte md5[] =  md.digest(token.getBytes());
			
			//base64编码--任意二进制编码明文字符   adfsdfsdfsf
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
			
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		
	}
	
}
表单处理Servlet

public class DoFormServlet extends HttpServlet {

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

		
		boolean b = isToken(request);  //判断用户是否是重复提交
		if(b==true){
			System.out.println("请不要重复提交");
			return;
		}
		
		request.getSession().removeAttribute("token");
		
		System.out.println("处理用户提交请求!!");
		
	}

	private boolean isToken(HttpServletRequest request) {
		
		String client_token = request.getParameter("token");
		if(client_token==null){
			return true;
		}
		
		String server_token = (String) request.getSession().getAttribute("token");
		if(server_token==null){
			return true;
		}
		
		if(!client_token.equals(server_token)){
			return true;
		}
		
		return false;
	}

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

		doGet(request, response);
	}

}



posted @ 2013-11-20 22:47  今晚打酱油_  阅读(364)  评论(0编辑  收藏  举报