歡迎您光臨本站 註冊首頁

java中的過濾器Filter的使用配置

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

  最近做項目的時候,用到了過濾器的使用配置

  作為項目的筆記記錄

  import java.io.IOException;

  import java.io.PrintWriter;

  import javax.servlet.Filter;

  import javax.servlet.FilterChain;

  import javax.servlet.FilterConfig;

  import javax.servlet.RequestDispatcher;

  import javax.servlet.ServletException;

  import javax.servlet.ServletRequest;

  import javax.servlet.ServletResponse;

  import javax.servlet.http.HttpServlet;

  import javax.servlet.http.HttpServletRequest;

  import javax.servlet.http.HttpServletResponse;

  import javax.servlet.http.HttpSession;

  /**

  * 過濾器使用:用戶沒用登錄,不可以在瀏覽器輸入地址訪問頁面

  * @author Administrator

  *

  */

  public class OnlineFilter extends HttpServlet implements Filter {

  public void doFilter(ServletRequest request, ServletResponse response,

  FilterChain chain) throws IOException, ServletException {

  RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");

  HttpServletRequest req =(HttpServletRequest)request;

  HttpServletResponse res =(HttpServletResponse)response;

  HttpSession session =req.getSession(true);

  //從session 裡面獲取用戶名的信息

  String user =(String)session.getAttribute("user");

  //判斷如果沒有取到用戶信息,就跳轉到登陸頁面,提示用戶進行登陸

  if(user == null || "".equals(user)){

  //跳轉到登陸的頁面,進行用戶登錄

  dispatcher.forward(request,response);

  System.out.println("用戶沒有登錄,請登陸!");

  }else{

  System.out.println("用戶已經登陸成功,允許繼續操作!");

  }

  chain.doFilter(request, response);

  }

  public void init(FilterConfig arg0) throws ServletException {

  }

  /**

  * Destruction of the servlet. <br>

  */

  public void destroy() {

  super.destroy(); // Just puts "destroy" string in log

  }

  public void init() throws ServletException {

  }

  }

  Web.xml配置

  <!-- 過濾器的 過濾用戶登陸的session對象 -->

  <filter>

  <filter-name>sessionFilter</filter-name>

  <filter-class>biz.sdna.cbrc.util.OnlineFilter</filter-class>

  </filter>

  <filter-mapping>

  <filter-name>sessionFilter</filter-name>

  <url-pattern>/jsp/*</url-pattern>

  </filter-mapping>


[火星人 ] java中的過濾器Filter的使用配置已經有454次圍觀

http://coctec.com/docs/java/show-post-60781.html