filter应用案例二:权限控制

filter可以用来进行权限控制,比如admin文件夹下的文件只允许管理员进入,那么,可以给admin文件夹加上一个过滤器:

简单代码示例:

 1 import java.io.IOException;
 2 import javax.servlet.Filter;
 3 import javax.servlet.FilterChain;
 4 import javax.servlet.FilterConfig;
 5 import javax.servlet.ServletException;
 6 import javax.servlet.ServletRequest;
 7 import javax.servlet.ServletResponse;
 8 import javax.servlet.http.HttpServletRequest;
 9 public class RCFilter implements Filter {
10     public void destroy() {}
11     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
12         HttpServletRequest req=(HttpServletRequest) request;
13         String admin=(String) req.getSession().getAttribute("admin");    //查看管理员是否登录,这里只是用于演示,方便起见,用字符串代替管理员类
14         if(admin==null)
15         {
16             System.out.println("您不是管理员,不得进入该页面!");    //管理员未登录,不放行
17         }
18         else chain.doFilter(request, response);            //放行
19     }
20     public void init(FilterConfig fConfig) throws ServletException {}
21 }
RCFilter
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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" version="2.5">
 3   <display-name></display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.jsp</welcome-file>
 6   </welcome-file-list>
 7   <filter>
 8     <display-name>RCFilter</display-name>
 9     <filter-name>RCFilter</filter-name>
10     <filter-class>RCFilter</filter-class>
11   </filter>
12   <filter-mapping>
13     <filter-name>RCFilter</filter-name>
14     <url-pattern>/admin/*</url-pattern>
15   </filter-mapping>
16 </web-app>
web.xml

 

posted @ 2016-11-17 20:11  凌晨。。。三点  阅读(287)  评论(0编辑  收藏  举报