Application of the filter JavaWeb

A: coarse-grained access control (whether or login interception to intercept the user name admin privileges)

    Ideas: the filter can be checked before the Web component is called ServletRequest object, modify the body of the request header or request; filters can check ServletResponse object to modify the response content header or response after the invoked Web component, it is determined whether to enter the page it should be written in Filter

UserFilter
. 1  public  class UserFilter the implements the Filter {
 2      public  void the destroy () {}
 . 3      public  void the doFilter (the ServletRequest Request, Response the ServletResponse,
 . 4              the FilterChain catena alberghiera) throws IOException, {ServletException
 . 5          / * 
. 6           * 1. get session
 . 7           * 2. Analyzing session whether there is a domain admin, if present, release
 8           * 3. session to determine whether there is a domain username, if present, release, or fight back login.jsp, and tell it not blind to stay up to
 9           * / 
10          the HttpServletRequest REQ = ( the HttpServletRequest) Request;
 . 11         String name = (String)req.getSession().getAttribute("admin");
12         if(name != null) {
13             chain.doFilter(request, response);
14             return;
15         }
16         
17         name = (String)req.getSession().getAttribute("username");
18         if(name != null) {
19             chain.doFilter(request, response);
20         } else {
21             req.setAttribute("msg", "您啥都不是,不要瞎溜达!");
22             req.getRequestDispatcher("/login.jsp").forward(request, response);
23         }
24     }
25     public void init(FilterConfig fConfig) throws ServletException { }
26 }
View Code

 

AdminFilter.java
. 1  public  class AdminFilter the implements the Filter {
 2      public  void the destroy () {}
 . 3      public  void the doFilter (the ServletRequest Request, Response the ServletResponse,
 . 4              the FilterChain catena alberghiera) throws IOException, {ServletException
 . 5          / * 
. 6           * 1. get session
 . 7           * 2. Analyzing session whether there is a domain admin, if present, release
 8           * 3. session to determine whether there is a domain username, if present, release, or fight back login.jsp, and tell it not blind to stay up to
 9           * / 
10          the HttpServletRequest REQ = ( the HttpServletRequest) Request;
 . 11         Name = String (String) the req.getSession () the getAttribute ( "ADMIN." );
 12 is          IF (name =! Null ) {
 13 is              the chain.doFilter (Request, Response);
 14          } the else {
 15              req.setAttribute ( "MSG" "You may be a what, but certainly not an administrator!" );
 16              req.getRequestDispatcher ( "/ the login.jsp" ) .forward (Request, the Response);
 17          }
 18      }
 19      
20 }
View Code

 

LoginServlet
. 1  public  class the LoginServlet the extends the HttpServlet {
 2      public  void the doPost (the HttpServletRequest Request, the HttpServletResponse Response)
 . 3              throws ServletException, IOException {
 . 4          Request.setCharacterEncoding ( "UTF-. 8" );
 . 5          the response.setContentType ( "text / HTML; charset = UTF- 8 " );
 . 6          
. 7          / * 
8           * 1. Get the user name
 9           * 2 determines whether the user name contained itcast
 10           * 3. If included, the administrator is
 11           * 4. If not, ordinary members is
 12           * 5 save the user name should log on to the session
13          * 6. 转发到index.jsp
14          */
15         String username = request.getParameter("username");
16         if(username.contains("itcast")) {
17             request.getSession().setAttribute("admin", username);
18         } else {
19             request.getSession().setAttribute("username", username);
20         }
21         request.getRequestDispatcher("/index.jsp").forward(request, response);
22     }
23 }
View Code

 

Two: the number of access points ip statistics website

 

Statistical work will need to run before all the resources, then it can be placed in the Filter.

We do not intend to do this filter to intercept operation! Because we are just used for statistics.

What things to load data statistics. Map <String, Integer>

The entire site needs only to a Map!

Map When to create (using ServletContextListener, complete the creation of when the server starts, and only to the ServletContext), Map save to go! (Map saved to the ServletContext !!!)

  • Map need to store data in the Filter

  • Map need to use the page, the print data in the Map

AListener.java
. 1  public  class aListener the implements of ServletContextListener {
 2      / ** 
. 3       * Map created when the server starts, to save the ServletContext
 . 4       * / 
. 5      public  void the contextInitialized (ServletContextEvent SCE) {
 . 6          // Create Map 
. 7          Map <String, Integer> Map = new new a LinkedHashMap <String, Integer> ();
 . 8          // get the ServletContext 
. 9          the ServletContext application = sce.getServletContext ();
 10          // save the application to the map 
. 11          application.setAttribute ( "map", map);
12     }
13  
14  
15     public void contextDestroyed(ServletContextEvent sce) {
16     }
17 }
View Code
 
AFilter.java
. 1  public  class the AFILTER the implements the Filter {
 2      Private the FilterConfig config;
 . 3      public  void the destroy () {
 . 4      }
 . 5      public  void the doFilter (the ServletRequest Request, Response the ServletResponse,
 . 6              the FilterChain catena alberghiera) throws IOException, ServletException {
 . 7          / * 
. 8           * 1. give application the map
 9           * 2. get the current request from the client ip address
 10           * 3. Check whether the ip access number corresponding to the presence of the map, if present, the number of +1 and then go back and save
 11           * 4. If you do not have this ip , then that is the first visit to the site, set up visits 1
12           * / 
13          / * 
14           * 1. give Appliction
 15           * / 
16          the ServletContext App = config.getServletContext ();
 . 17          the Map <String, Integer> Map = (the Map <String, Integer>) app.getAttribute ( "Map" ) ;
 18          / * 
19           * 2. Get the client ip address
 20 is           * / 
21 is          String ip = request.getRemoteAddr ();
 22 is          / * 
23 is           * judgment 3.
 24           * / 
25          IF (map.containsKey (ip)) { / / the ip present in the map, described is not the first access 
26 is              int CNT =as map.get (ip);
 27              map.put (ip, CNT +. 1 );
 28          } the else { // the ip does not exist in the map, that is the first visit 
29              map.put (ip,. 1 );
 30          }
 31 is          app.setAttribute ( "map", map); // the map app and put back in the 
32          
33 is          the chain.doFilter (Request, Response); // sure release 
34      }
 35   
36   
37 [      / ** 
38       * server will start the implementation of this method, but this method is performed only once!
39       * / 
40      public  void the init (the FilterConfig fconfig) throws ServletException {
41         this.config = fConfig;
42     }
43 }
View Code
 

show.jsp

1 <table align="center" border="1" width="50%">
2   <tr><td>ip</td><td>次数</td></tr>
3    <c:forEach items="${applicationScope.map}"  var="entry">
4      <tr>
5      <td>${entry.key }</td>
6      <td>${entry.value }</td>
7      </tr>
8    </c:forEach>
9 </table>
View Code

 

Three: the whole station to solve garbled characters (POST and GET Chinese coding problem)

RequestFilter
 1     public void doFilter(ServletRequest request,  ServletResponse response, FilterChain chain) throws  IOException, ServletException {
 2          request.setCharacterEncoding("utf-8");
 3          
 4          HttpServletRequest req =  (HttpServletRequest)request;
 5          if(req.getMethod().equals("GET")){
 6               EncodingRequest er = new  EncodingRequest(req);
 7               chain.doFilter(er, response);
 8          }else if(req.getMethod().equals("POST")){
 9               chain.doFilter(request, response);
10          }
11          
12      }
View Code
 
EncodingServlet
 
1     public void doPost(HttpServletRequest request,  HttpServletResponse response)
2               throws ServletException, IOException {
3           response.setContentType("text/html;charset=utf-8");
4          String username=  request.getParameter("username");
5          response.getWriter().print(username);
6      }
7  
View Code

 

EncodingRequest
 1 public class EncodingRequest  extends  HttpServletRequestWrapper{
 2      private HttpServletRequest req;
 3      public EncodingRequest(HttpServletRequest request)  {
 4          super(request);
 5          // TODO Auto-generated constructor stub
 6          this.req=request;
 7      }
 8      public String getParameter(String name){
 9          String value = req.getParameter(name);
10          try {
11          value =new  String(value.getBytes("iso-8859-1"),"utf-8");
12               
13          } catch (UnsupportedEncodingException e) {
14               // TODO Auto-generated catch block
15               e.printStackTrace();
16          }
17          return value;
18      }
19 }
View Code

 

Renderings:

         
 
 
 

Guess you like

Origin www.cnblogs.com/Yzengxin/p/11204585.html