1. 程式人生 > >java中cookie的操作(通過cookie實現簡單的單點登入)

java中cookie的操作(通過cookie實現簡單的單點登入)

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
}


}