java中cookie的操作(通过cookie实现简单的单点登录)
(一)取得cookie中的相关信息
Cookie[] cookies = request.getCookies();
String username = "";
String password = "";
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equalsIgnoreCase("xabpoUsername")) {
username = c.getValue();
} else if (c.getName().equalsIgnoreCase("xabpoPassword")) {
password = c.getValue();
}
}
}
(二)将登陆用户的用户名和密码保存到cookie中
Cookie cookieUsername = new Cookie("xabpoUsername",userForm.getUserID());
Cookie cookiePassword = new Cookie("xabpoPassword",userForm.getPassword()) cookieUsername.setMaxAge(60*60*24); //设定有效时间
cookiePassword.setMaxAge(60*60*24);
cookieUsername.setPath("/");
cookiePassword.setPath("/");
cookieUsername.setDomain(".xasourcing.gov.cn"); // 设定有效域
cookiePassword.setDomain(".xasourcing.gov.cn");
response.addCookie(cookieUsername);
response.addCookie(cookiePassword);
(三)退出登录的时候将cookie删除
Cookie[] cookies=request.getCookies();
try
{
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String cookieName = cookies[i].getName();
if (cookieName.equals("xabpoUsername")
|| cookieName.equals("xabpoPassword")) {
cookies[i].setValue(null);
cookies[i].setPath("/");
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
}
}
}
}catch(Exception e)
{
LogUtil.error(this.getClass(), e.getMessage(), e);
}
删除的时候上面标红的几段比较重要
(1)设为null这句如果没有的话,如果你退出登录的逻辑后紧跟着一个从cookie中取值的操作,这时就
能从cookie中取到删除过的值。
(2) cookies[i].setPath("/");这句,如果不和设定cookie的时候的path不对应起来,就有删不掉cookie的可能。
(3) cookies[i].setMaxAge(0);这个就是设定该cookie立马过期的操作。
Cookie[] cookies = request.getCookies();
(二)将登陆用户的用户名和密码保存到cookie中
(三)退出登录的时候将cookie删除
Cookie[] cookies=request.getCookies();
删除的时候上面标红的几段比较重要
(1)设为null这句如果没有的话,如果你退出登录的逻辑后紧跟着一个从cookie中取值的操作,这时就
能从cookie中取到删除过的值。
(2) cookies[i].setPath("/");这句,如果不和设定cookie的时候的path不对应起来,就有删不掉cookie的可能。
(3) cookies[i].setMaxAge(0);这个就是设定该cookie立马过期的操作。
三个文件:
一个过滤器:
package com.njupt.sso.filter;
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;
public class AutoLoginFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if(request.getSession().getAttribute("user")== null){
Cookie[] cs = request.getCookies();
if (cs != null && cs.length > 0) {
for (Cookie c : cs) {
String cName = c.getName();
if (cName.equals("sso")) {
String userName = c.getValue();
request.getSession().setAttribute("user", userName);
}
}
}
}
chain.doFilter(request, resp);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
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;
public class AutoLoginFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if(request.getSession().getAttribute("user")== null){
Cookie[] cs = request.getCookies();
if (cs != null && cs.length > 0) {
for (Cookie c : cs) {
String cName = c.getName();
if (cName.equals("sso")) {
String userName = c.getValue();
request.getSession().setAttribute("user", userName);
}
}
}
}
chain.doFilter(request, resp);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
一个登陆文件
package com.njupt.sso.servlet;
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 {
/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(userName != null && password != null){
if(userName.equals(password)){//登录成功,实际应查询数据库
request.getSession().setAttribute("user", userName);
//向客户端写入cookie
Cookie c = new Cookie("sso",userName);
c.setMaxAge(3600);//1小时
c.setDomain(".njupt.com");//www.bbs.njupt.com www.news.njupt.com
c.setPath("/");
response.addCookie(c);
}
}
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
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 {
/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(userName != null && password != null){
if(userName.equals(password)){//登录成功,实际应查询数据库
request.getSession().setAttribute("user", userName);
//向客户端写入cookie
Cookie c = new Cookie("sso",userName);
c.setMaxAge(3600);//1小时
c.setDomain(".njupt.com");//www.bbs.njupt.com www.news.njupt.com
c.setPath("/");
response.addCookie(c);
}
}
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
一个web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>autoLogin</filter-name>
<filter-class>com.njupt.sso.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>autoLogin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.njupt.sso.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>autoLogin</filter-name>
<filter-class>com.njupt.sso.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>autoLogin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.njupt.sso.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
主页index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<c:choose>
<c:when test="${not empty sessionScope.user}">
欢迎你:${sessionScope.user}
</c:when>
<c:otherwise>
你还没有登录,请先登录:
<form action="<%=path %>/login" method="post">
userName:<input type="text" name="userName"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</c:otherwise>
</c:choose>
</body>
</html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<c:choose>
<c:when test="${not empty sessionScope.user}">
欢迎你:${sessionScope.user}
</c:when>
<c:otherwise>
你还没有登录,请先登录:
<form action="<%=path %>/login" method="post">
userName:<input type="text" name="userName"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</c:otherwise>
</c:choose>
</body>
</html>