首頁  >  文章  >  Java  >  cookie、session和java過濾器結合實作登陸程序

cookie、session和java過濾器結合實作登陸程序

高洛峰
高洛峰原創
2017-01-18 14:20:051459瀏覽

cookie、session和過濾器通常都是用在web應用中,cookie和session用來保存一定的數據,過濾器Filter則是在瀏覽器發出請求之後,而後台執行特定的請求之前發生一定的作用。之所以把這三個放一起,是因為有很多時候都會是把他們結合在一起使用,例如有些登陸程序。

cookie是瀏覽器的機制,session是伺服器的機制,但是實際上cookie也是由伺服器產生的,之後傳回給瀏覽器的,並不是瀏覽器本身產生。當瀏覽器發送某個請求時,如果擁有有效的cookie則會把這個cookie帶在一起。

之所有會有cookie的使用,是因為http協議原本是無狀態協議,也就是說透過http協議本身,伺服器不能判斷瀏覽器是否之前訪問過。

Filter和servlet的寫法相似,編寫相關程式碼的時候需要實作Filter介面並重寫相關的方法,通常會改變較多的是doFilter方法。 Filter程式碼寫好以後如果需要發生效用,需要像設定servlet一樣在web.xml中 進行一定的設定。

以下是一個簡單的結合cookie、session、Servlet和Filter的登陸範例程式碼:

定義一個使用者實體類,充當資料庫數據,這裡使用單例模式,保證只存在一個實例物件:

package models; 
  
/** 
 * 用户信息实体类 
 * 
 * @author tuzongxun123 
 * 
 */
public class UserModel { 
  private String userName; 
  private String password; 
  
  // 单例模式,保证只有一个用户对象实例 
  public static UserModel getInstance() { 
    UserModel user = new UserModel("zhangsan", "123456"); 
    return user; 
  
  } 
  
  private UserModel(String userName, String pasword) { 
    this.userName = userName; 
    this.password = pasword; 
  } 
  
  public String getUserName() { 
    return userName; 
  } 
  
  public String getPassword() { 
    return password; 
  } 
  
}

使用者登陸輸入資訊index.jsp介面,在form表單的action中使用jsp的特性取得專案路徑:

<%@ page language="java" import="java.util.*" 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>cookieAndFilterTest</title> 
</head> 
<body> 
   <form action="<%=request.getContextPath() %>/loginServlet" method="post"> 
    userName:<input type="text" name="userName" /></br> 
    password:<input type="password" name="password" /></br> 
    <input type="submit" value="login"/> 
   </form> 
</body> 
</html>

對應的後台servlet:

package servletTest; 
  
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; 
import javax.servlet.http.HttpSession; 
import models.UserModel; 
  
public class LoginServlet extends HttpServlet { 
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    this.doPost(req, resp); 
  } 
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    String userName = req.getParameter("userName"); 
    String password = req.getParameter("password"); 
    // 模拟数据库数据 
    UserModel user = UserModel.getInstance(); 
    String dbUserName = user.getUserName(); 
    String dbPassword = user.getPassword(); 
    if (dbUserName.equals(userName) && dbPassword.equals(password)) { 
      // 用户名和密码都匹配,证明登陆成功,设置session和cookie 
      HttpSession session = req.getSession(); 
      session.setAttribute("userName", userName); 
      session.setAttribute("password", password); 
      Cookie cookie = new Cookie("userName", userName); 
      Cookie cookie2 = new Cookie("password", password); 
      // 设置cookie的存储时长 
      cookie.setMaxAge(60); 
      cookie2.setMaxAge(60); 
      // 把cookie发送给浏览器 
      resp.addCookie(cookie); 
      resp.addCookie(cookie2); 
      // 转发请求到用户列表 
      req.getRequestDispatcher("/userList").forward(req, resp); 
    } else { 
      // 转发请求到登陆页面 
      req.getRequestDispatcher("index.jsp").forward(req, resp); 
    } 
    ; 
  
  } 
  
}

上邊登陸後跳轉的請求:

package servletTest; 
  
import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import models.UserModel; 
  
public class UserListServlet extends HttpServlet { 
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    this.doPost(req, resp); 
  } 
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    UserModel user = UserModel.getInstance(); 
    //在浏览器中打印出用户列表书数据 
    resp.getWriter().write( 
        "userName:" + user.getUserName() + "," + "password:"
            + user.getPassword()); 
  
  } 
  
}

專案。

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">   
  
 <!-- 访问时的项目名称 -->
 <display-name>cookieAndFilterTest</display-name> 
 <!-- servlet配置 -->
 <servlet> 
   <servlet-name>login</servlet-name> 
   <servlet-class>servletTest.LoginServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>login</servlet-name> 
   <url-pattern>/loginServlet</url-pattern> 
 </servlet-mapping> 
  
 <servlet> 
   <servlet-name>userList</servlet-name> 
   <servlet-class>servletTest.UserListServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>userList</servlet-name> 
   <url-pattern>/userList</url-pattern> 
 </servlet-mapping> 
  
 <!-- 过滤器设置,浏览其发送请求后首先会走这里 -->
 <filter> 
   <filter-name>loginFilter</filter-name> 
   <filter-class>filterTest.FilterTest</filter-class> 
 </filter> 
 <filter-mapping> 
   <filter-name>loginFilter</filter-name> 
   <url-pattern>/*</url-pattern> 
 </filter-mapping> 
  
 <!-- 输入项目名访问的默认页面 -->
 <welcome-file-list> 
  <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 
</web-app>

java過濾器程式碼:

package filterTest; 
  
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; 
import models.UserModel; 
  
public class FilterTest implements Filter { 
  
  @Override
  public void destroy() { 
  
  } 
  
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, 
      FilterChain chain) throws IOException, ServletException { 
    // 登陆请求、初始请求直接放行 
    HttpServletRequest req = (HttpServletRequest) request; 
    HttpServletResponse resp = (HttpServletResponse) response; 
    String uri = req.getRequestURI(); 
    if ("/cookieAndFilterTest/loginServlet".equals(uri) 
        || "/cookieAndFilterTest/".equals(uri)) { 
      // 放行 
      chain.doFilter(request, response); 
      return; 
    } 
  
    // 不是登陆请求的话,判断是否有cookie 
    Cookie[] cookies = req.getCookies(); 
    if (cookies != null && cookies.length > 0) { 
      String userName = null; 
      String password = null; 
      // 判断cookie中的用户名和密码是否和数据库中的一致,如果一致则放行,否则转发请求到登陆页面 
      for (Cookie cookie : cookies) { 
        if ("userName".equals(cookie.getName())) { 
          userName = cookie.getValue(); 
        } 
        if ("password".equals(cookie.getName())) { 
          password = cookie.getValue(); 
        } 
      } 
      UserModel user = UserModel.getInstance(); 
      if (user.getUserName().equals(userName) 
          && user.getPassword().equals(password)) { 
        chain.doFilter(request, response); 
        return; 
      } else { 
        // 重定向到登陆界面 
        req.getRequestDispatcher("/index.jsp").forward(req, resp); 
        return; 
      } 
    } else { 
      req.getRequestDispatcher("/index.jsp").forward(req, resp); 
      return; 
    } 
  } 
  
  @Override
  public void init(FilterConfig arg0) throws ServletException { 
  
  } 
  
}

以上就是本文的全部內容,希望對大家學習java程式設計有所幫助。

更多cookie、session和java過濾器結合實現登陸程序相關文章請關注PHP中文網!



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn