spring mvc拦截器 需求:在controller层的方法上,使用自定义注解的方式 不拦截指定请求

原来是在controller类上实现此需求
缺点:只能是整个controller类下的方法全部放开拦截,不能放开其中某个方法,颗粒度太高。
现实现在方法上增加注解,更加细颗粒度。

1.首先是自定义的Annocation

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcludeInterceptor {

}

2.创建spring mvc 的拦截器

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.hao.xu.lang.interceptor.InterceptorOne">
            bean>
        mvc:interceptor>
mvc:interceptors>
package com.hao.xu.lang.interceptor;

import com.hao.xu.lang.annotation.ExcludeInterceptor;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class InterceptorOne implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

		//获取到目标方法对象
		HandlerMethod method = (HandlerMethod) o;
		//取到方法上的注解
		ExcludeInterceptor methodAnnotation = method.getMethodAnnotation(ExcludeInterceptor.class);
		if (Objects.isNull(methodAnnotation)) {
			//无此注解的一律拦截
			httpServletResponse.sendRedirect("http://localhost:8080/html/interceptor.html");
			return false;
		}

		System.out.println("Interceptor_preHandle_One");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

		System.out.println("Interceptor_postHandle_One");
	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

		System.out.println("Interceptor_afterCompletion_One");
	}
}

3.测试controller

@RestController
public class HelloController {

	@RequestMapping(value = "/hi")
	public String hello(HttpSession session) {

		System.out.println("hi");
		return "hi";
	}

	@RequestMapping(value = "/hello")
	@ExcludeInterceptor
	public String hello2(HttpSession session) {

		System.out.println("hello");
		return "hello";
	}

}

4.测试
现在访问 http://localhost:8080/hi.do 被拦截重定向到了error界面
spring mvc拦截器 需求:在controller层的方法上,使用自定义注解的方式 不拦截指定请求_第1张图片
再访问 http://localhost:8080/hello.do
spring mvc拦截器 需求:在controller层的方法上,使用自定义注解的方式 不拦截指定请求_第2张图片

你可能感兴趣的:(spring,mvc)