SpringMVC basics (4)

SpringMVC foundation (four)

Interceptor

Interceptors are similar to filters, but they are different from filters:The interceptor is based on AOP!

The interceptor acts on the request process of the client requesting the server.

Define an interceptor

The custom interceptor must implement the HandlerInterceptor interface!

  • Write a class that implements the HandlerInterceptor interface
  • Configure Interceptor into spring-mvc.xml to implement AOP

true : intercept and release; false : intercept and live

public class MyIntercepetor implements HandlerInterceptor {
    
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("处理前");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("处理后");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        System.out.println("清理");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.qiu.controller"/>

    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <!--
            要拦截的路径 /**:根请求下的所有请求,也就是所有请求。
            /user/**:根请求下的user请求下的所有请求,也就是user请求下的所有子请求
            -->
            <mvc:mapping path="/**"/>
            <bean class="com.qiu.config.MyIntercepetor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

Generally, just write a pre-processing interception!

But it is not like the filter that needs to execute the following code, the following code will not be executed after the return in the interceptor!

One of the business scenarios of the interceptor: the user can access the homepage (main.jsp) only after logging in, and the user will intercept and jump to the login page when entering the homepage without logging in; the user cannot directly access the login page, only click on the index page Go to the login page.

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    // 直接进入main页面
    @RequestMapping("goMain")
    public String goMain(){
    
    
        return "main";
    }

    // 直接进入login页面
    @RequestMapping("/goLogin")
    public String goLogin(){
    
    
        return "login";
    }

    // 登陆后,将判别用户登录字段放到session中,然后转发到main页面
    @RequestMapping("/login")
    public String login(HttpSession httpSession, String username, String pwd){
    
    
        // 将用户的用户名放进session,用来判别用户是否登录
        httpSession.setAttribute("userLoginInfo", username);
        return "main";
    }
}
public class LoginInterceptor implements HandlerInterceptor {
    
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        HttpSession session = request.getSession();
        // 如果用户登录后,放行
        if (session.getAttribute("userLoginInfo") != null){
    
    
            return true;
            // 如果用户请求login处理器(就是在提交登录时),放行
        }else if (request.getRequestURI().contains("login")){
    
    
            return true;
            // 如果用户请求goLogin处理器(跳转到login页面),放行
        }else if (request.getRequestURI().contains("goLogin")){
    
    
            return true;
        }

        // 其他情况都转发到登录页面:像直接访问goMain请求(直接进入首页)
        // 使用request进行请求转发,因为重定向客户端是访问不到WEB-INF下的
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.qiu.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.qiu.config.MyIntercepetor"/>
        </mvc:interceptor>
        
        <mvc:interceptor>
            <!--
            要拦截的路径 /**:根请求下的所有请求,也就是所有请求。
            /user/**:根请求下的user请求下的所有请求,也就是user请求下的所有子请求
            -->
            <mvc:mapping path="/user/**"/>
            <bean class="com.qiu.config.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

Guess you like

Origin blog.csdn.net/qq_43477218/article/details/114263451