程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> cookie、session和java過濾器聯合完成上岸法式

cookie、session和java過濾器聯合完成上岸法式

編輯:關於JAVA

cookie、session和java過濾器聯合完成上岸法式。本站提示廣大學習愛好者:(cookie、session和java過濾器聯合完成上岸法式)文章只能為提供參考,不一定能成為您想要的結果。以下是cookie、session和java過濾器聯合完成上岸法式正文


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

項目web.xml設置裝備擺設:

<?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法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved