Filter filter Principle and login implementation, Filter filter Principle

Source: Internet
Author: User

Filter filter Principle and login implementation, Filter filter Principle

Filter API
The Servlet Filter API contains three interfaces in the javax. servlet package: Filter interface, FilterChain interface, and FilterConfig interface.
Filter interface (source code)

public interface Filter {    public void init(FilterConfig filterConfig) throws ServletException;    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;    public void destroy();}

All filters must implement the Filter interface. This interface defines three methods: init, doFilter0, and destory:
(1) init (FilterConfig filterConfig)
When a web application is started, the web server creates each registered Filter instance object based on the configuration information in the web. xml file and saves it in the memory of the server. After the Web Container creates a Filter object instance, it immediately calls the init method of the Filter object. The Init method is only executed once in the Filter lifecycle. When the web Container calls the init method, A FilterConfig object containing the Filter configuration and runtime environment will be passed (the usage of FilterConfig is similar to that of ServletConfig ). The FilterConfig object can be used to obtain the ServletContext object and the initialization parameters of the filter configured in the deployment descriptor.
(2) doFilter (ServletRequest request, ServletResponse response, FilterChain chain)

The doFilter () method is similar to the service () method of the Servlet interface. When the client requests the target resource, the container will call the doFilter () method of the filter associated with the target resource. The request and response parameters are the requests and corresponding objects passed by the previous Filter in the web Container or Filter chain. The chain parameter is the object representing the current Filter chain. After a specific operation is completed, you can call the chain of the FilterChain object within the doFilter method of the Current Filter object. the doFilter (request, response) method can deliver the request to the next Filter or target Servlet program in the Filter chain for processing. It can also directly return the response information to the client, or use the forward () of RequestDispatcher () the include () method and the sendRedirect () method of HttpServletResponse redirect requests to other resources. The request and Response parameters of this method are ServletRequest and ServletResponse. That is to say, the use of filters does not depend on specific protocols.
(3) public void destroy ()
Called before the Web Container unmounts the Filter object. This method is only executed once in the lifecycle of the Filter. In this method, resources used by the filter can be released.
FilterChain interface (source code)

public interface FilterChain {    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException;}

(1) doFilter (ServletRequest request, ServletResponse response)
This method is provided to developers by the Servlet container, which is used to call the filter chain of resource requests in sequence. The filter chain is called through FilterChain. If it is the last filter, the next resource is called.
FilterConfigThe interface (source code) FilterConfig interface retrieves the Filter Name, initialization parameters, and the active Servlet context.

Public interface FilterConfig {// returns the web. the name of the filter defined in the xml deployment file is public String getFilterName (); // return the servlet context of the caller public ServletContext getServletContext (); // return the String form of the value of the initialization parameter of the filter. If the parameter does not exist, the returned nul1.name is the initialization parameter name public String getInitParameter (String name ); // return all the initialization parameter values of the filter in the form of Enumeration. If no initialization parameter exists, the return value is empty public Enumeration getInitParameterNames ();}

 

I understand the basic concepts and source code of Filter. The following describes how to use the Filter to implement logon filtering.

Requirement: access page A (the page that can be accessed only after logon) --> not logged on --> jump to the logon page --> after successful login, Go to page

Custom HttpFilter

Import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/***** HttpFilter */public abstract class HttpFilter implements Filter {// Save the filterConfig object private FilterConfig filterConfig; /*** directly return the filterConfig object * @ return */public FilterConfig getFilterConfig () {return filterConfig;}/*** it is not recommended that the subclass directly overwrite the object, the filterConfig member variable initialization may fail */@ Override public void init (FilterConfig filterConfig) throws ServletException {this. filterConfig = filterConfig; init ();}/*** the initialization method inherited by the subclass. The filterConfig object */private void init () is obtained using the getFilterConfig () method () {}/*** native doFilter method converts ServletRequest and ServletResponse into HttpServletRequest and response in the method, * and calls doFilter (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) method */@ Override public void doFilter (ServletRequest req, res, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req; response = (response) res; doFilter (request, response, filterChain);}/*** abstract method, customized for http requests, required Method * @ param request * @ param response * @ param filterChain * @ throws IOException * @ throws ServletException */public abstract void doFilter (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException; @ Override public void destroy (){}}View Code

Configure CommonFilter in web. xml

    <filter>        <filter-name>commonFilter</filter-name>        <filter-class>com.gcx.emall.Filter.CommonFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>commonFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

Login filter CommonFilter

Import java. io. IOException; import javax. servlet. filterChain; import javax. servlet. servletException; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. slf4j. logger; import org. slf4j. loggerFactory; public class CommonFilter extends HttpFilter {private final Logger log = LoggerFactory. getLogger (CommonFilter. class); @ Override public void doFilter (HttpSer VletRequest request, HttpServletResponse response, FilterChain) throws IOException, servletException {log.info ("================= intercept get requests ================ "); if ("GET ". equalsIgnoreCase (request. getMethod () {RequestUtil. saveRequest (request);} String requestUri = request. getRequestURI (); String contextPath = request. getContextPath (); String url = requestUri. substring (contextPath. length ()); If ("/login ". equals (url) {filterChain. doFilter (request, response); return;} else {String username = (String) request. getSession (). getAttribute ("user"); if (username = null) {log.info ("intercepted: Jump to the login page! "); Request. getRequestDispatcher ("/page/index1.jsp "). forward (request, response);} else filterChain. doFilter (request, response );}}}

RequestUtil save, get the request, and encrypt the request page

Public class RequestUtil {private static final Logger logger = LoggerFactory. getLogger (RequestUtil. class); private static final Base64 base64 = new Base64 (true); public static final String LAST_PAGE = "lastPage "; // The public static final String REDIRECT_HOME = "/" page accessed when you are not logged on; // The public static final String LOGIN_HOME = "/index. jsp "; // the page that is displayed after Successful Logon/*** Save the current request */public static void saveRequest (Http ServletRequest request) {request. getSession (). setAttribute (LAST_PAGE, RequestUtil. hashRequestPage (request); logger. debug ("sessionID of the intercepted url: {}", request. getSession (). getId (); logger. debug ("save request for {}", request. getRequestURI ();}/*** encrypted request page * @ param request * @ return */public static String hashRequestPage (HttpServletRequest request) {String reqUri = request. getRequestURI (); String Query = request. getQueryString (); if (query! = Null) {reqUri + = "? "+ Query;} String targetPage = null; try {targetPage = base64.encodeAsString (reqUri. getBytes ("UTF-8");} catch (UnsupportedEncodingException ex) {// this does not happen} return targetPage ;} /*** retrieve the previously stored request * @ return */public static String retrieveSavedRequest (HttpServletRequest request) {HttpSession session = request. getSession (); if (session = null) {return REDIRECT_HOME;} String HashedlastPage = (String) session. getAttribute (LAST_PAGE); if (HashedlastPage = null) {return LOGIN_HOME;} else {return retrieve (HashedlastPage );}} /*** decrypt the request page * @ param targetPage * @ return */public static String retrieve (String targetPage) {byte [] decode = base64.decode (targetPage ); try {String requestUri = new String (decode, "UTF-8"); int I = requestUri. indexOf ("/", 1); return requestUri. substring (I);} catch (UnsupportedEncodingException ex) {// this does not happen return null ;}}}View Code

LoginCOntroller

@ RequestMapping (value = "/hello", method = RequestMethod. GET)
Public String testHello (String test ){
Log.info ("the Hello method is executed! ");
Return "loginSuccess ";
}
@ RequestMapping (value = "/login", method = RequestMethod. POST) public String login (HttpServletRequest request, String userName, String password) {log.info ("the login method is executed! "); Password = DigestUtils. md5Hex (password); User user = userService. findUser (userName, password); if (user! = Null) {request. getSession (). setAttribute ("userId", user. getId (); request. getSession (). setAttribute ("user", userName); return "redirect:" + RequestUtil. retrieveSavedRequest (request); // jump to the access page} else {log.info ("user does not exist"); request. getSession (). setAttribute ("message", "the user name does not exist. Please log on again"); return "index ";}}

Finally, several jsp pages are required for login. jsp, index. jsp (Home Page, accessible to anyone), loginSuccess. jsp, you also need to add a test testHello method in the controller to meet the previously mentioned requirements.

Note: We filter all requests, but we should not intercept static resources css, js, and image and allow them. You can specify

<! -- Do not intercept static files --> <servlet-mapping> <servlet-name> default </servlet-name> <url-pattern>/js/* </url-pattern> <url-pattern>/css/* </url-pattern> <url-pattern>/image/* </url-pattern> <url-pattern>/fonts/* </ url-pattern> </servlet-mapping>

I want to write a summary of the Filter and SpringMVC interceptor, but I feel that the length is somewhat long and I will introduce it later.

 

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.