1.cookie是什么?
cookie是web应用当中非常常用的一种技术,用于储存某些特定的用户信息。
2.cookie的作用?
在用户登陆时将用户的信息存放在cookie中,用户在一定的时间中再次登陆时不需要输入用户名和密码直接跳转到下一个界面。
3.设置cookie
Cookie cookie = new Cookie("key", "value");
cookie.setMaxAge(saveTime*24*60*60);
生存周期默认时间为秒,如果设置为负值的话,则为浏览器进程Cookie(内存中保存),关闭浏览器就失效。
cookie.setPath("/test/test2");
设置Cookie路径,不设置的话为当前路径(对于Servlet来说为request.getContextPath() + web.xml里配置的该Servlet的url-pattern路径部分) 。
response.addCookie(cookie);
4.读取cookie
该方法可以读取当前路径以及“直接父路径”的所有Cookie对象,如果没有任何Cookie的话,则返回null。如果设置了路径使用这个方法也没有值。
Cookie[] cookies = request.getCookies();
5.删除cookie
Cookie cookie = new Cookie("key", null);
cookie.setMaxAge(0);
设置为0为立即删除该Cookie;
cookie.setPath("/test/test2");
删除指定路径上的Cookie,不设置该路径,默认为删除当前路径Cookie;
response.addCookie(cookie);
下面看一个例子,这是模拟126邮箱登陆的小功能。建立一个名为AutoLoginFilter的project,包结构如下:
project下有三个java文件、两个jsp还有个html,
CheckLogin.java代码如下:
public class CheckLogin {
public static boolean login(String username, String password) {
if ("admin".equals(username) && "123456".equals(password)) {
return true;
} else {
return false;
}
}
}
IndexFilter.java代码如下:
package com.bx.course;
/** *//**
* Filter可以实现对请求的过滤和重定向等,也就是说可以操作request和response,session等对象,listner只能监听到以上对象的属性的修改。
*/
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
System.out.println("every request pass here haha");
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
Cookie[] cookies = request.getCookies();
// Cookie cookie = new Cookie("user",null);
// cookie.setMaxAge(0);
// response.addCookie(cookie);
String[] cooks = null;
String username = null;
String password = null;
if (cookies != null) {
for (Cookie coo : cookies) {
String aa = coo.getValue();
System.out.println("1");
cooks = aa.split("==");
if (cooks.length == 2) {
System.out.println(cooks[0]+cooks[1]);
username = cooks[0];
password = cooks[1];
}
}
}
System.out.println("cookie username | " + username);
System.out.println("cookie password | " + password);
if (CheckLogin.login(username, password)) {
System.err.println("check successfully cookie data ");
request.getSession().setAttribute("username",username);
request.getRequestDispatcher("/main126.jsp").forward(request, response);
}else{
arg2.doFilter(request,response );
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
LoginServlet.java代码如下:
package com.bx.course;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("username");
String password=request.getParameter("password");
String savetime=request.getParameter("saveTime");
System.out.println("usrename "+username+" password "+password);
if(CheckLogin.login(username, password)){
if(null!=savetime){
int saveTime=Integer.parseInt(savetime);//这里接受的表单值为天来计算的
int seconds=saveTime*24*60*60;
Cookie cookie = new Cookie("user", username+"=="+password);
cookie.setMaxAge(seconds);
response.addCookie(cookie);
}
request.setAttribute("username",username);
request.getRequestDispatcher("/main126.jsp").forward(request,response);
}else{
request.getRequestDispatcher("/failure.jsp").forward(request,response);
}
}
}
web.xml配置文件代码如下:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.bx.course.IndexFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/login.html</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.bx.course.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<welcome-file-list>
<welcome-file>main126.jsp</welcome-file>
</welcome-file-list>
login.html代码如下:
<html>
<head>
</head>
<body>
<form action="login.do">
126邮箱登录<br/><br/>
用户名:<input type="text" name="username" ><br/>
密 码:<input type="text" name="password" ><br/>
<select name="saveTime">
<option value="366">一年</option>
<option value="183">半年</option>
<option value="30">一个月</option>
<option value="7">一周</option>
</select><br/>
<input type="submit" value="登录" />
</form>
</body>
</html>
main126.jsp代码如下:
<html>
<head>
<title>测试cookie</title>
</head>
<body>
<h2>登录成功,欢迎${username}的到来 126邮箱</h2><br/>
<h3>测试cookie的功能
</body>
</html>
failure.jsp代码如下:
<body>
Login failure <br>
</body>
运行效果:
在IE地址栏中输入http://localhost:8080/LoginFilter/login.html
显示如下界面:
输入用户名:admin 密码:123456 选择保存时间,然后点击登陆,就会进入以下界面:
在保存时间内再次在IE地址栏中输入:http://localhost:8080/LoginFilter/login.html
就会直接进入登陆成功界面。如果用户名或密码不正确则会进入以下界面: