1。 利用Struts 进行账户权限管理
这里只有一个com.micas.utils.test.MyFilter定义,但是在web app启动实例化了2个instance,分别读入2个参数。并且,指定了触发着两个instance的uri 的mapping.
1 <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
4 version="2.4">
5
6 <servlet>
7 <servlet-name>action</servlet-name>
8 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
9 <init-param>
10 <param-name>config</param-name>
11 <param-value>/WEB-INF/struts-config.xml
12 </param-value>
13 </init-param>
14 </servlet>
15
16 <!-- Action Servlet Mapping -->
17 <servlet-mapping>
18 <servlet-name>action</servlet-name>
19 <url-pattern>*.do</url-pattern>
20 </servlet-mapping>
21
22
23 <display-name>pogo</display-name>
24
25 <filter>
26 <filter-name>patGeneral</filter-name>
27 <filter-class>com.micas.utils.test.MyFilter</filter-class>
28 <init-param>
29 <param-name>role</param-name>
30 <param-value>general</param-value>
31 </init-param>
32 </filter>
33
34 <filter>
35 <filter-name>patManager</filter-name>
36 <filter-class>com.micas.utils.test.MyFilter</filter-class>
37 <init-param>
38 <param-name>role</param-name>
39 <param-value>manager</param-value>
40 </init-param>
41 </filter>
42
43 <filter-mapping>
44 <filter-name>patManager</filter-name>
45 <url-pattern>/view/pat/manager/*</url-pattern>
46 </filter-mapping>
47
48 <filter-mapping>
49 <filter-name>patGeneral</filter-name>
50 <url-pattern>/view/pat/general/*</url-pattern>
51 </filter-mapping>
52
53
54 </web-app>
MyFilter 代码如下:
1 package com.micas.utils.test;
2
3
4 import javax.servlet.Filter;
5 import javax.servlet.FilterChain;
6 import javax.servlet.FilterConfig;
7 import javax.servlet.ServletException;
8 import javax.servlet.ServletRequest;
9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServletRequest;
11 import java.io.IOException;
12
13
23 public class MyFilter implements Filter
24 {
25 private String role;
26
27 public void init(FilterConfig config) throws ServletException
28 {
29 role = config.getInitParameter("role");
30 System.out.println("role is "+role);
31 config.getServletContext().setAttribute("test",role);
32
33 }
34
35 public void doFilter(ServletRequest request, ServletResponse response,
36 FilterChain chain)
37 throws IOException, ServletException
38 {
39
40 if("manager".equalsIgnoreCase(role)){
41 System.out.println("you are in as a manager");
42 }
43 else if("general".equalsIgnoreCase(role)){
44 System.out.println("you are in as general");
45 }
46 else{
47 System.out.println("something not right");
48 }
49 HttpServletRequest hRequest = (HttpServletRequest)request;
50 System.out.println("the file sends the request is "+hRequest.getRequestURI());
51 chain.doFilter(request, response);
52 }
53
54 public void destroy()
55 {
56 }
57 }
58