java之Filter用法(實現請求的攔截過濾,以及權限判斷)

Filter實現登陸權限的過濾實例

               Fileter簡介:

                                  Filter 主要是實現攔截客戶端到達servlet到頁面請求,並且能夠修改請求(HttpServletRequest)的頭和數據。

                                (實現登陸的登陸判斷,以及相關權限的判斷)

                                Filter還可以實現在HttpServletResponse到達客戶端的攔截,可以檢查修改(HttpServletResponse)的頭和數據

            1、Filter實現類

  public class DoLogin implements Filter{
 
 //獲取配置參數信息
 private FilterConfig config;
 //初始化
 public void init(FilterConfig config)
 {
  this.config=config;
 }
 //實現銷燬
 public void destroy()
 {
  this.config=null;
 }
 //實現doFilter方法
 public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
  throws IOException,ServletException
 {
  //獲取Filter的配置參數
  String encoding=config.getInitParameter("encoding");
  String loginPage=config.getInitParameter("LoginPage");
  String proPage=config.getInitParameter("ProPage");
  //設置編碼集
  request.setCharacterEncoding(encoding);
  //把強求轉化爲HttpServletRequest
  HttpServletRequest hreq=(HttpServletRequest)request; 
  //獲取登錄信息
  HttpSession session=hreq.getSession(true);
  //獲取請求頁面
  String hreqPath=hreq.getServletPath();
  //判斷頁面信息,登錄user有信息,登錄頁面時login.jsp或者是prologin.jsp
  if(session.getAttribute("user")==null
    &&!hreqPath.endsWith(loginPage)
    &&!hreqPath.endsWith(proPage))
  {
   //跳轉到登錄頁面
   request.setAttribute("tip", "你還沒有登錄");
   request.getRequestDispatcher(loginPage).forward(request, response);
  }
  else
  {
   //放行
   chain.doFilter(request, response);
   
  }
  
 }
}

2、配置web.xml

    <filter>
    <filter-name>dologin</filter-name>
    <filter-class>lee.DoLogin</filter-class>
    <init-param>
     <param-name>encoding</param-name>
     <param-value>GBK</param-value>
    </init-param>
    <init-param>
     <param-name>LoginPage</param-name>
     <param-value>/login.jsp</param-value>
    </init-param>
    <init-param>
     <param-name>ProPage</param-name>
     <param-value>/proLogin.jsp</param-value>
    </init-param>
   </filter>
   <!-- 攔截URL-->
   <filter-mapping>
    <filter-name>dologin</filter-name>
    <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

3、在web容器中創建3個頁面login.jsp  ;prologin.jsp;other.jsp

4、最終結果展示:登陸系統以後可以任意查看其它頁面,而沒有登陸時,查看其它頁面將會被攔截返回登陸頁,並給出提示信息。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章