Home> Java> javaTutorial> body text

Spring+SpringMVC+MyBatis in-depth learning and construction (17) - SpringMVC interceptor

PHP中文网
Release: 2017-07-03 17:30:26
Original
1359 people have browsed it

Please indicate the source:

As mentioned earlier: Spring+SpringMVC+MyBatis in-depth learning and construction (16) - SpringMVC annotation development (advanced)

1.Interceptor definition

Spring Web MVC's processor interceptor is similar to the filter Filter in Servlet development, which is used to pre-process and post-process the processor.

Define the interceptor and implement the HandlerInterceptor interface. Three methods are provided in the interface.

package joanna.yan.ssm.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class HandlerInterceptor1 implements HandlerInterceptor{ //执行Handler完成执行此方法 //应用场景:统一异常处理,统一日志处理  @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("HandlerInterceptor1......afterCompletion"); } //进入Handler方法之后,返回modelAndView之前执行 //应用场景从modelAndView出发:将公用的模型数据(比如菜单导航)在这里传到视图,也可以在这里同意指定视图  @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("HandlerInterceptor1......postHandle"); } //进入Handler方法之前执行 //用于身份认证、身份授权 //比如身份认证,如果认证不通过表示当前用户没有登录,需要此方法拦截不再向下执行。  @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("HandlerInterceptor1......preHandle"); //return false表示拦截,不向下执行 //return true表示放行 return true; } }
Copy after login

2.Interceptor configuration

There is a large interceptor chain in struts. It is a common thing. You can add it to any action link and let it intercept. But spring's interceptor is not global.

2.1 Configure an interceptor for a certain mapping

The springmvc interceptor performs interception settings for HandlerMapping. If interception is set in a HandlerMapping, the handler that is successfully mapped by the HandlerMapping will eventually use the interceptor.

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="handlerInterceptor1"/> <ref bean="handlerInterceptor2"/> list> property> bean> <bean id="handlerInterceptor1" class="joanna.yan.ssm.interceptor.HandlerInterceptor1"/> <bean id="handlerInterceptor2" class="joanna.yan.ssm.interceptor.HandlerInterceptor2"/>
Copy after login

Generally not recommended.

2.2 Configure global interceptors for all mappings

springmvc can configure similar global interceptors, and the springmvc framework injects the configured global-like interceptors into each HandlerMapping.

 <mvc:interceptors>  <mvc:interceptor>  <mvc:mapping path="/**"/> <bean class="joanna.yan.ssm.interceptor.HandlerInterceptor1">bean> mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="joanna.yan.ssm.interceptor.HandlerInterceptor2">bean> mvc:interceptor> mvc:interceptors>
Copy after login

3.Interception test

3.1 Testing requirements

Test the execution timing of each method of multiple interceptors.

3.2Write two interceptors

3.3 Both interceptors are allowed

Run log information:

HandlerInterceptor1...preHandle HandlerInterceptor2...preHandle HandlerInterceptor2...postHandle HandlerInterceptor1...postHandle HandlerInterceptor2...afterCompletion HandlerInterceptor1...afterCompletion
Copy after login

Summarize:

The preHandle method is executed in order, and postHandle and afterCompletion are executed in the reverse order of the interceptor configuration.

3.4 Interceptor 1 is allowed, Interceptor 2 is not allowed

Run log information:

HandlerInterceptor1...preHandle HandlerInterceptor2...preHandle HandlerInterceptor1...afterCompletion
Copy after login

Summarize:

Interceptor 1 is released, and the preHandle of interceptor 2 will be executed.

The preHandle of interceptor 2 will not be released, and the postHandle and afterCompletion of interceptor 2 will not be executed.

As long as there is an interceptor that does not release, postHandle will not be executed.

3.5 Interceptor 1 is not allowed, Interceptor 2 is not allowed

Run log information:

HandlerInterceptor1...preHandle
Copy after login

The preHandle of interceptor 1 is not released, and postHandle and afterCompletion will not be executed.

The preHandle of interceptor 1 is not released, and interceptor 2 is not executed.

4. Summary

Apply the interceptor based on the test results.

For example: Unified log processing interceptor, if the interceptor preHandle needs to be changed, it must be released and placed at the first position in the interceptor chain.

For example: login authentication interceptor, placed at the first position in the interceptor chain. The permission verification interceptor is placed after the login interceptor. (Because the permissions are verified after the login is passed)

5.Interceptor application (implementing login authentication)

5.1 Requirements

(1) User request url

(2) Interceptor performs interception verification

If the requested URL is a public address (a URL that can be accessed without logging in), let it pass

If the user session does not exist, jump to the login page.

If the user session exists, release it and continue the operation.

5.2 Login and exit controller methods

package joanna.yan.ssm.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { //登录 @RequestMapping("/login") public String login(HttpSession session, String username, String password) throws Exception{ //调用service进行用户身份认证 //... //在session中保存用户身份信息 session.setAttribute("username", username); return "redirect:items/queryItems.action"; } //退出 @RequestMapping("/logout") public String logout(HttpSession session) throws Exception{ //清除session  session.invalidate(); return "redirect:items/queryItems.action"; } }
Copy after login

5.3 Login authentication interception implementation

5.3.1LoginInterceptor

public class LoginInterceptor implements HandlerInterceptor{ //执行Handler完成执行此方法 //应用场景:统一异常处理,统一日志处理  @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("HandlerInterceptor1......afterCompletion"); } //进入Handler方法之后,返回modelAndView之前执行 //应用场景从modelAndView出发:将公用的模型数据(比如菜单导航)在这里传到视图,也可以在这里同意指定视图  @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("HandlerInterceptor1......postHandle"); } //进入Handler方法之前执行 //用于身份认证、身份授权 //比如身份认证,如果认证不通过表示当前用户没有登录,需要此方法拦截不再向下执行。  @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("HandlerInterceptor1......preHandle"); //获取请求的url String url=request.getRequestURI(); //判断url是否是公开地址(实际使用时要将公开地址配置到文件中) //这里公开地址是登录提交的地址 if(url.indexOf("login.action")>=0){ //如果进行登录提交,放行 return true; } //判断session HttpSession session=request.getSession(); String username=(String) session.getAttribute("username"); if(username!=null){ //身份存在,放行 return true; } //执行到这里,表示用户身份需要认证,跳转登录页面 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); //return false表示拦截,不向下执行 //return true表示放行 return false; } }
Copy after login

5.3.2 Interceptor configuration

Configuration in springmvc.xml under classpath:

If this article is helpful to you, please tip me on WeChat~

The above is the detailed content of Spring+SpringMVC+MyBatis in-depth learning and construction (17) - SpringMVC interceptor. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!