Spring自定义注解实现HandlerInterceptorAdapter 拦截请求

 注解类 UnLoginAccessAnnotation.java

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

/**
 * 允许未登录访问注解
 */
@Target({ ElementType.METHOD })// 作用范围:方法(也可以扩大到类上,看需求决定)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UnLoginAccessAnnotation{
	String value() default "";
}

登录访问拦截 LoginAccessHandlerInterceptor.java 该类继承了 org.springframework.web.servlet.handler.HandlerInterceptorAdapter ,重写了 preHandle 方法。


public class LoginAccessHandlerInterceptor extends HandlerInterceptorAdapter {

    /**
     * 拦截器
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    	HandlerMethod hm = null;
    	Method method = null;
    	if(handler instanceof HandlerMethod) {
    		hm = (HandlerMethod) handler;
            method = hm.getMethod();// 获取方法
    	} else {
    		return true;
		}
		// 该方法是否添加 允许未登录访问注解
        if (method !=null &&  method.isAnnotationPresent(UnLoginAccessAnnotation.class)) { 
			// 不拦截
        	return true;
        }
        String token = CookiesUtils.getToken(request, Const.LoginInfoConstant.JSESSION_ID);
		// 拦截 token 为空
        if(StringUtils.isEmpty(token)){
            return toLogin(request, response); 
        }
		// 不为空时解析
        LoginUsersInfo loginUserInfo = JwtUtils.parseUserToken(request,token);
		// jwt 解析失败
        if(null == loginUserInfo){
            return toLogin(request, response); 
        }
		// 将用户信息放入request中
        request.setAttribute("loginUserInfo", loginUserInfo);
        return true;
    }

}

 xml配置


  	
  		
  		
			
			
			
	        
    	    
         	
         	
         	
			
		
	

注解配置

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorRegister extends WebMvcConfigurerAdapter{

    private static final Logger logger = LoggerFactory.getLogger(InterceptorRegister.class);

    /*
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new LoginAccessHandlerInterceptor());
        super.addInterceptors(registry);
    }

}

接口类

@Controller
@RequestMapping("/topSearch")
public class TopSearchController {

	private static final Log log = LogFactory.getLog(TopSearchController.class);
	
	@Autowired
	private TopSearchService topSearchService;
	
	/**
	 * 查询热搜数据,默认前十条
	 * @param query
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/get")
	@SkipIntercept // 未登录允许访问
	public Result> get(TopSearchQuery query) throws Exception {
		return topSearchService.getTopSearchByRange(query.getBegin(), query.getEnd());
	}

}

看看 HandlerInterceptorAdapter 类 

package org.springframework.web.servlet.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Abstract adapter class for the {@link AsyncHandlerInterceptor} interface,
 * for simplified implementation of pre-only/post-only interceptors.
 *
 * @author Juergen Hoeller
 * @since 05.12.2003
 */
public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {

	/**
	 * This implementation always returns {@code true}.
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 在方法被调用前执行,如果返回true,则继续调用下一个拦截器,返回false,则中断执行。
		return true;
	}

	/**
	 * This implementation is empty.
	 */
	@Override
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
			// 在方法执行后调用
	}

	/**
	 * This implementation is empty.
	 */
	@Override
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
			// 在整个请求处理完毕后进行回调,DispatcherServlet完全处理完请求、视图渲染完毕或者调用方已经拿到响应。
	}

	/**
	 * This implementation is empty.
	 */
	@Override
	public void afterConcurrentHandlingStarted(
			HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	}

}

 

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