Java Filter (simplified authentication)

Source: Internet
Author: User

Recently looking at the filter, just realized the filter's Simplified authentication function:

Simplify Authentication with filters:

In a Web application, a key use case for a filter is to protect an application from access by unauthorized users. Customer support applications developed for multinational parts companies use a very primitive authentication mechanism to protect pages. You may have noticed that many places in the application contain the same duplicate code that is used to check for authentication:

1 if NULL {2   response.sendredirect ("login"); 3   return ;           4 }

At the same time you might think that a simpler way to authenticate is to create a public static method on a class to perform the check and invoke it everywhere. Indeed, this will reduce the duplication of code, but it will still cause problems in calling the method in multiple places. As the number of servlets increases in an application, the call to that static method is also increased.

   So the filter to simplify the certification is still very useful, I made a small demo, the idea is to call Listservlet,listservlet Redirect to index.jsp, of course, I weblistener in the dynamic configuration filter is the path " /index.jsp "page is configured. So before jumping to the index.jsp page, the code in the filter will be executed (to determine if you are logged in, the login status allows you to jump to index.jsp, the non-login status will redirect to Login.jsp to let the user log in).

Next is Listservlet (I go directly to this servlet to start the entire demo test)

Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet (name= "Listservlet", urlpatterns= "/list") Public classListservletextendsHttpServlet {/**     *      */    Private Static Final LongSerialversionuid = 1L; @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {System.out.println ("Listservet"); Resp.sendredirect (Req.getservletcontext (). Getcontextpath ()+ "/index.jsp"); } @Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); }}

This is the corresponding filter authenticationfilter

Importjava.io.IOException;Importjava.time.Instant;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;ImportJavax.servlet.annotation.WebFilter;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession; Public classAuthenticationfilterImplementsfilter{@Override Public voiddestroy () {//TODO auto-generated Method Stub} @Override Public voidDoFilter (servletrequest req, Servletresponse resp, filterchain chain)throwsIOException, servletexception {if(Req.getattribute ("userName") = =NULL{(httpservletresponse) resp). Sendredirect (Req.getservletcontext (). Getcontextpath ()+ "/login.jsp"); }Else{chain.dofilter (req, resp); }} @Override Public voidInit (Filterconfig arg0)throwsservletexception {//TODO auto-generated Method Stub            }}

In the Web listener, the appropriate filter is configured

1  PackageDeep.web.listener;2 3 Importjava.util.Collection;4 5 Importjavax.servlet.FilterRegistration;6 ImportJavax.servlet.ServletContext;7 Importjavax.servlet.ServletContextEvent;8 ImportJavax.servlet.ServletContextListener;9 ImportJavax.servlet.annotation.WebListener;Ten  One ImportDeep.web.filter.AuthenticationFilter; A  - @WebListener -  Public classConfiguratorImplementsservletcontextlistener{ the  - @Override -      Public voidcontextdestroyed (servletcontextevent arg0) { -         //TODO auto-generated Method Stub +          -     } +  A @Override at      Public voidcontextinitialized (Servletcontextevent event) { -ServletContext context =Event.getservletcontext (); -          -Filterregistration.dynamic registration = Context.addfilter ("Authenticationfilter",NewAuthenticationfilter ()); -          -Registration.setasyncsupported (true); inSystem.out.println ("contextinitialized"); -          toRegistration.addmappingforurlpatterns (NULL,false, "/index.jsp"); +          -         /*This is my test, determine whether the URL is configured, and the output URL*/ the System.out.println (Registration.geturlpatternmappings (). IsEmpty ()); *collection<string> str =registration.geturlpatternmappings (); $ System.out.println (str);Panax Notoginseng     } -  the}

I'll paste the loginservlet, too.

1  PackageDeep.web.controller;2 3 Importjava.io.IOException;4 5 Importjavax.servlet.ServletException;6 ImportJavax.servlet.annotation.WebServlet;7 ImportJavax.servlet.http.HttpServlet;8 Importjavax.servlet.http.HttpServletRequest;9 ImportJavax.servlet.http.HttpServletResponse;Ten  One  A@WebServlet (name= "Userservlet", urlpatterns= "/user") -  Public classUserservletextendshttpservlet{ -     Private Static Final LongSerialversionuid = 1L; the @Override -     protected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException { -          -     } + @Override -     protected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException { +System.out.println ("Userservlet"); AString method= Req.getparameter ("method")); at         if(Method.equals ("Login")) { -System.out.println ("Loginservlet"); -String name = Req.getparameter ("name"); -String Password = req.getparameter ("Password"); -             if(Name.equals ("test") && password.equals ("test"))) { -Req.getsession (). SetAttribute ("UserName", "name" ); inResp.sendredirect (Req.getservletcontext (). Getcontextpath () + "/list.jsp"); -}Else{ toSYSTEM.OUT.PRINTLN ("Login Failed ~"); +Resp.sendredirect (Req.getservletcontext (). Getcontextpath () + "/login.jsp"); -             } the         } *     } $}

Next is the output, I will go directly into the listservlet→ filter (if already logged in) → Enter index.jsp

→ Enter filter (if not logged in) → Enter login.jsp

The advantage of this approach is that if you want to modify the authentication algorithm, you only need to modify the filter to protect the resources in the application. Before, you will have to modify all the servlets.

Actually should not use request to authenticate, should use session, forehead, head son ache ... sorry

Reference book: Java Web Advanced Programming

Java Filter (simplified authentication)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.