Servlet—Session

1. Session简介

Session是服务器端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的session对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务。

1.1 Session的生命周期

Session的创建:

在一个会话中,当浏览器首次访问Servlet,并且该Servlet中有request.getSession()语句时才会创建一个Session对象。

Session的摧毁:

1)服务器会把长时间没有活动的Session从服务器内存中清除,此时Session便失效。Tomcat中Session的默认失效时间为30分钟(可以在web.xml中配置<session-config>标签来设定失效时间)。

2)调用Session的invalidate方法时会摧毁Session对象

1.2 Session和Cookie比较

Cookie是把用户的数据写给用户的浏览器;Session技术把用户的数据写到用户独占的session中。

1.3 Session演示:

假如在一个购物网站上,有一个主页,有一个购买按钮,有一个结账按钮:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网站首页</title>
</head>
<body>
	
	<a href="/day07/SessionDemo">购买</a>
	<a href="/day07/SessionDemo2">结账</a>
	
</body>
</html>


SessionDemo:

package com.oner.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//购买Servlet
public class SessionDemo extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession();
		session.setAttribute("name", "洗衣机");
		
		out.print("购买成功,请结账!");

	}

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

}


SessionDemo2:

package com.oner.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//支付Servlet
public class SessionDemo2 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		HttpSession session = request.getSession();
		String product = (String) session.getAttribute("name");
		out.print("您购买的商品是:" + product+"<br/>结账成功!");

	}

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

}



在浏览器地址栏中输入:http://localhost:8080/day07/index.html,回车:


点击“购买”,网页自动跳转到了SessionDemo页面,显示“购买成功,请结账!”:



返回主页,点击“结账”,网页自动跳转到了SessionDemo2页面,显示“您购买的商品是:洗衣机,结账成功!”:



从上面可以看出Session的基本工作过程,其实就是在用户访问SessionDemo页面时,服务器为这个用户创建一个Session对象,里面存放在这个用户的一些数据(在这里是购买了洗衣机),,当用户进入SeesionDemo2页面时,再从Seesion对象中拿到这个用户的数据(购买了洗衣机)。

是设想这样一种场景:有用户A和用户B同时访问购买页面,且购买的商品不同,然后又同时访问支付页面,服务器如何判断哪个Seesion对象中存放的是用户A的数据,哪个存放的是用户B的数据呢?

其实Session是基于Cookie实现的,如果在点击购买按钮时打开httpwatch,会发现如下信息:


在相应信息的响应头中发现Set-Cookie为:JSESSIONID=1A3AFFD9F1A0E53534823F71F5A3BCB2; Path=/day07。说明当用户的一些数据存储在Session对象后,服务器也会为将该Session对象的id信息以Cookie的形式发送给浏览器。

当点击结账按钮时,查看httpwatch:


发现在响应头中Cookie的值为JSESSIONID=1A3AFFD9F1A0E53534823F71F5A3BCB2,说明在用户点击结账按钮时,同时会将为他服务的Session对象的id发送给服务器。服务器收到请求后,会先匹配id是否一致,如果一致则继续为其服务。

明白了上面的原理,这里再做一个实验,先进入主页,点击购买按钮:


然后重启浏览器,进入主页后,点击结账按钮:


发现显示购买的商品是:null。这是怎么回事呢?其实这时以为如果没有JSESSIONID这个Cookie的默认时效是本次会话,如果中途关闭浏览器,这个JSESSIONID就失效了。可以自己手动设定下JSESSIONID的时效。现在修改下SessionDemo:

package com.oner.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//购买Servlet
public class SessionDemo extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession();
		session.setAttribute("name", "洗衣机");
		
		out.print("购买成功,请结账!");
		
		String sessionId= session.getId();
		Cookie cookie=new Cookie("JSESSIONID",sessionId);
		cookie.setPath("/day07");
		cookie.setMaxAge(30*60);//设置cookie时效30min
		
		response.addCookie(cookie);
		
	}

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

}


这时再打开主页,点击购买按钮,查看httpwatch:


发现Set-Cookie后的值设定了Cookie的时效。再重启浏览器,进入主页点击结账:



1.4 URL重写

通过上面的学习,了解了Session的一些实现细节。这儿继续讨论,如果浏览器禁用Cookie,那么会是什么效果呢?我们可以试着去做一下,进入主页后点击“购买”,然后返回主页点击“结账”,结果:


这是什么原因造成的呢?试想下,如果浏览器禁用Cookie,也就是说当服务器给浏览器发送JSESSIONID时,浏览器并不会接收它,所以用户使用浏览器发起下一次请求时并不会携带JSESSIONID,服务器会认为这是一个新的用户在访问,所以最后输出的null。

想要解决以上问题,可以使用URL重写。什么是URL重写呢?如果浏览器不支持Cookie或用户阻止了所有Cookie,可以把会话ID附加在HTML页面中所有的URL上,这些页面作为响应发送给客户。这样,当用户单击URL时,会话ID被自动作为请求行的一部分而不是作为头行发送回服务器。这种方法称为URL重写。

HttpResponse有两个方法可以实现URL重写。

encodeURL(java.lang.String url):用于对表单action和超链接的url地址进行重写

encodeRedirectURL(java.lang.String url):用于对sendRedirect方法后的url地址进行重写。

在之前我们主页使用index.html,现在我们新建一个WelcomeServlet,用它来代表主页。

package com.oner.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//首页
public class WelcomeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 每个新用户一访问主页,就为该用户创建一个Session。
		request.getSession();

		// 重写购买和结账页面的URL
		String url1 = response.encodeURL("/day07/Session");
		String url2 = response.encodeURL("/day07/Session2");

		out.print("<a href='" + url1 + " '>购买</a><br/>");
		out.print("<a href='" + url2 + " '>结账</a>");

	}

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

}


现在我们打开httpwatch,在浏览器地址中输入:http://localhost:8080/day07/WelcomeServlet,回车:



点击“购买”:


查看httpwatch:



发现请求行中多了JSESSIONID,说明浏览器发送请求时将属于本次会话的JSESSIONID也发送到了服务器,服务器就可以根据id来判断这次访问是不是之前用户进行的访问。现在返回主页,点击“结账”按钮:


查看httpwatch信息:



2. Session的应用

2.1 实现简单购物

ListBookServlet:

package com.oner.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//代表网站首页,列出所有商品
public class ListBookServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		request.getSession();// 一定要注意,先得到Session对象

		out.print("本网站有如下商品:<br/>");
		Map<String, Book> map = DB.getAll();
		Set<Entry<String, Book>> set = map.entrySet();
		for (Entry<String, Book> entry : set) {
			Book book = entry.getValue();
			// url重写
			String url = response.encodeURL(request.getContextPath()
					+ "/BuyServlet?id=" + book.getId());
			out.print(book.getName() + "<a href='" + url
					+ "' target=_black>购买</a><br/>");
		}

	}

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

}

class DB {

	// 使用LinkedHashMap是为了保证存储和取出的顺序一致
	private static Map<String, Book> map = new LinkedHashMap<String, Book>();

	static {

		map.put("1", new Book("1", "javaweb开发", "老张", "一本好书"));
		map.put("2", new Book("2", "spring开发", "老黎", "一本好书"));
		map.put("3", new Book("3", "hibernate开发", "老佟", "一本好书"));
		map.put("4", new Book("4", "struts开发", "老毕", "一本好书"));
		map.put("5", new Book("5", "ajax开发", "老张", "一本好书"));

	}

	public static Map<String, Book> getAll() {
		return map;
	}

}

class Book {

	private String id;
	private String name;
	private String author;
	private String description;

	public Book() {
		super();
	}

	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;
	}

}


BuyServlet:

package com.oner.shopping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//完成购买的页面
public class BuyServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String id = request.getParameter("id");
		Book book = DB.getAll().get(id);

		HttpSession session = request.getSession(false);// 因为用户访问首页已经在服务器创建了Session对象,所以这里只是拿到

		// 手工以cookie形式发送sessionid,以解决关闭浏览器后上次购买的东西还在。
		/*
		 * Cookie cookie = new Cookie("JSESSIONID",session.getId());
		 * cookie.setMaxAge(30*60); cookie.setPath("/day07");
		 * response.addCookie(cookie);
		 */

		// 先得到用户购买书的容器
		List<Book> bookList = (List<Book>) session.getAttribute("bookList");
		// 如果之前没有购买书,则bookList==null
		if (bookList == null) {
			bookList = new ArrayList<Book>();
			session.setAttribute("bookList", bookList);
		}
		bookList.add(book);

		// 这里使用请求转发后,如果在BuyServlet页面一直刷新,那么会一直重复之前购买的书籍,所以应该使用请求重定向
		// request.getRequestDispatcher("/ListCartServlet").forward(request,
		// response);

		// url重写
		// request.getContextPath()是为了得到web应用路径
		String url = response.encodeRedirectURL(request.getContextPath()
				+ "/ListCartServlet");

		response.sendRedirect(url);

	}

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

}


ListCartServlet:

package com.oner.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		HttpSession session = request.getSession(false);// 这儿不是新创建session对象,而是得到已经存在的session对象
		if (session == null) {
			out.print("你没有购买任何商品");
			return;
		}

		out.print("您购买了以下商品:<br/>");
		List<Book> bookList = (List<Book>) session.getAttribute("bookList");
		for (Book book : bookList) {
			out.print(book.getName());
		}

	}

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

}


2.2 完成用户登录

在一个大的网站中,会有很多Servlet,假如很多网页的操作的前提是用户登陆,假如一个用户在登陆页面登陆成功了,其他Servlet如何知道该用户是否登陆成功了呢?可以在登陆页面将该用户的session中存入一个登陆成功的标记,这样,其他Servlet就可以通过查询该用户的Session中的登陆标记来确定是否让该用户去继续其他操作。

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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>网站首页</title>
</head>
<body>
	欢迎您:${user.username}  
	<a href="/day07/login.html">登录</a> 
	<a href="/day07/LogoutServlet">退出登录</a>
	<br />
	<br />
	<br />

</body>
</html>


login.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head> 
<body>

	<form action="/day07/LoginServlet" method="post">
	<!-- 这里一定要注意下,name="username"一定要加上双引号 -->
		用户名: <input type="text" name="username" /><br />
		 密码: <input type="password" name="password" /><br />
		 <input type="submit" value="登陆"/>
	</form>
	
</body>
</html>


LoginServlet:

package com.oner.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//完成用户登录
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("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) {
			// 如果输入的username和password和数据库中的一致,则登陆成功
			if (user.getUsername().equals(username)
					&& user.getPassword().equals(password)) {
				// 登陆成功后需要设置该用户登陆成功的session标记
				request.getSession().setAttribute("user", user);
				// 重定向到首页
				response.sendRedirect(request.getContextPath() + "/index.jsp");
				return;
			}
		}

		out.print("用户名或密码不正确!");

	}

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

}

class DB {

	public static List<User> list = new ArrayList<User>();
	
	static {
		list.add(new User("aaa", "123"));
		list.add(new User("bbb", "123"));
		list.add(new User("ccc", "123"));
	}

	public static List<User> getAll() {
		return list;
	}

}


LogoutServlet:

package com.oner.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

	private static final long serialVersionUID = 1L;

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

		HttpSession session = request.getSession(false);
		if (session == null) {
			// 如果用户未登录,直接跳回主页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
			return;
		}

		session.removeAttribute("user");
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}

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

}


User.java:

package com.oner.login;

public class User {

	private String username;
	private String password;

	public User() {
		super();
	}

	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;
	}

}


2.3 防表单重复提交

下面来看一个用于模拟用户注册的示例。

注册页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form.html</title>
</head>
<body>
	<form action="/day07/DoFormServlet" method="post">
		用户名:<input type="text" name="username"/>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>


package com.oner.form;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//处理表单提交请求
public class DoFormServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String username = request.getParameter("username");

		try {
			// 模拟网络延迟3s
			Thread.sleep(1000 * 3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// 在控制台输入这句话来模拟想数据库中注册用户信息
		System.out.println("向数据库中注册用户~~~~");

	}

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

}


在浏览器地址栏中输入:http://localhost:8080/day07/form.html,回车:


在用户名中输入aaa,点击提交,发现没有反应,再点击一次提交,查看控制台:


发现输入了两次"向数据库中注册用户~~~~",说明表单重复提交了。为了防止这个问题,可以采用如下解决方式:

在服务器使用token拦截器。怎么理解呢?

1)当用户首次访问包含表单的页面时,服务器会在这次会话中产生一个令牌值,并创建一个session对象,同时将令

牌值保存到Session中然后将这个令牌值作为隐藏输入项的值,

2)当用户提交数据时,令牌值会随表单里的其他数据一起发送到服务器端。

3)服务器首先判断请求参数中的令牌值和Session中保存的令牌值是否相等,若相等,则清除Session中的令牌值,

然后执行数据处理操作。如果不相等,则提示用户已经提交过了表单。

FormServlet:

package com.oner.form;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

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

	private static final long serialVersionUID = 1L;

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

		// 产生随机数(表单号)
		TokenProcessor tp = TokenProcessor.getInstance();
		String token = tp.generateToken();

		// 将表单号存入Session域
		request.getSession().setAttribute("token", token);
		
		//将请求转发给form.jsp
		request.getRequestDispatcher("/form.jsp").forward(request, response);

	}

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

}

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 {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] md5 = md.digest(token.getBytes());// 得到数据指纹,长度为128位(16个字节)

			// base64编码--任意二进制编码明文字符
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);

		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
			// e.printStackTrace(); 为啥需要抛出RuntimeException异常呢?
		}

	}

}


form.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>form.jsp</title>
</head>
<body>
	<%-- 最后将表单数据(连通隐藏输入项token的值)提交到DoFormServlet --%>
	<form action="/day07/DoFormServlet" method="post">
		<%--从session域中拿到服务器产生的token值,赋值给隐藏输入项 --%>
		<input type="hidden" name="token" value="${token }"/>
		用户名:<input type="text" name="username"/><br/>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>


DoFormServlet:

package com.oner.form;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//处理表单提交请求
public class DoFormServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		/*
		 * String username = request.getParameter("username");
		 * 
		 * try { // 模拟网络延迟3s Thread.sleep(1000 * 3); } catch
		 * (InterruptedException e) { e.printStackTrace(); }
		 */

		boolean b = isTokenValid(request);
		if (!b) {
			System.out.println("请不要重复提交");
		} else {
			// 将得到的表单标记清除
			request.getSession().removeAttribute("token");
			// 模拟向数据库中注册用户信息
			System.out.println("向数据库中注册用户~~~~");
			String username = request.getParameter("username");
			try { // 模拟网络延迟5s
				Thread.sleep(1000 * 5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("注册用户完成~~~~");
		}

	}

	// 判断表单号是否有效
	private boolean isTokenValid(HttpServletRequest request) {

		String client_token = request.getParameter("token");
		// 客户机如果未携带表单号
		if (client_token == null) {
			return false;
		}
		String server_token = (String) request.getSession().getAttribute(
				"token");
		// 如果服务器端产生的表单号为空,说明之前已将提交过数据了
		if (server_token == null) {
			return false;
		}
		if (!client_token.equals(server_token)) {
			return false;
		}
		return true;
	}

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

}



在浏览器中访问:http://localhost:8080/day07/FormServlet,在表单中输入数据,点击提交:




点击后发现没有反应,再次点击提交。查看控制台:


此时点击刷新按钮:


2.4 一次性图片认证码

假设在登陆时设定了验证码,并且是一次性验证码,主要目的就是为了限制人们利用工具软件来暴力猜测密码。

登陆页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="/day07/LoginServlet2" method="post">
	<!-- 这里一定要注意下,name="username"一定要加上双引号 -->
		用户名: <input type="text" name="username" /><br />
		 密码: <input type="password" name="password" /><br />
		 认证码:<input type="text" name="imagecheckcode"/><img src="/day07/ImageServlet"/><br/>
		 <input type="submit" value="登陆"/>
	</form>
</body>
</html>


ImageServlet:

package com.oner.checkcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//用于输出随机图片
public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final int WIDTH = 120;
	private static final int HEIGHT = 25;

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

		// 在内存中构造一个类型为TYPE_INT_RGB的BufferedImage对象
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		// 得到图形对象
		Graphics2D graph = (Graphics2D) image.getGraphics();

		// 1.设置背景色
		setBackGround(graph);
		// 2.设置边框
		setBorder(graph);
		// 3.设置干扰线
		drawRandomLine(graph);
		
		// 4.写随机数,同时将该随机数放入Session中
		String random =drawRandomNum(graph);
		request.getSession().setAttribute("imagecheckcode", random);
		
		// 5.把图片写给客户机,再通知浏览器以图片方式打开数据,并且要通知浏览器不能缓存图片
		response.setHeader("Expires", "-1");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		response.setContentType("image/jpeg");
		ImageIO.write(image, "jpg", response.getOutputStream());

	}

	private String drawRandomNum(Graphics2D graph) {
		graph.setColor(Color.RED);
		graph.setFont(new Font("宋体", Font.BOLD, 20));
		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";

		StringBuffer sb  = new StringBuffer();
		
		int x = 5;
		for (int i = 0; i < 4; i++) {
			int degree = new Random().nextInt(30) % 30;// -30~30度
			graph.rotate(degree * Math.PI / 180, x, 20);// 设置旋转弧度
			String ch = base.charAt(new Random().nextInt(base.length())) + "";
			
			sb.append(ch);
			
			graph.drawString(ch, x, 20);
			graph.rotate(-degree * Math.PI / 180, x, 20);// 恢复旋转状态
			x += 30;
		}
		
		return sb.toString();
	}


	private void drawRandomLine(Graphics2D graph) {
		// 设置颜色为绿色
		graph.setColor(Color.GREEN);
		// 画5条干扰线
		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);
			// 绘制干扰线
			graph.drawLine(x1, y1, x2, y2);
		}
	}

	private void setBorder(Graphics2D graph) {
		// 设置颜色为蓝色
		graph.setColor(Color.BLUE);
		// 绘制矩形的边框
		graph.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
	}

	private void setBackGround(Graphics2D graph) {
		// 设置颜色为白色
		graph.setColor(Color.WHITE);
		// 填充一个矩形
		graph.fillRect(0, 0, WIDTH, HEIGHT);
	}

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

}


LoginServlet:

package com.oner.checkcode;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//完成登陆验证
public class LoginServlet2 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 由于要从客户端拿到中文数据,所以要设置编码格式
		request.setCharacterEncoding("UTF-8");

		// 处理注册请求之前,校验验证码是否有效
		String c_imagecheckcode = request.getParameter("imagecheckcode");
		String s_imagecheckcode = (String) request.getSession().getAttribute(
				"imagecheckcode");
		if (c_imagecheckcode != null && s_imagecheckcode != null
				&& c_imagecheckcode.equals(s_imagecheckcode)) {
			out.print("验证码正确");
		} else {
			out.print("验证码错误");
		}

	}

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

}


在浏览器地址栏中输入:http://localhost:8080/day07/login2.html,回车:


由于这里的登陆验证只是验证验证码,所以只需输入图片中的验证码即可:


点击登陆:


返回到登陆页面刷新下,然后输入错误的验证码,点击登陆:




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值