I found a good tutorial on this site on how to add request interceptors to specific controllers using annotations:
- Define the annotation
- Define the interceptor
- Add the interceptor to the path
- Use the annotation on the specific controller
https://programmer.group/how-do-spring-boot-2.x-add-interceptors.html
I know this question was how to add interceptors to all requests and that's answered already. I was searching the solution to add request interceptors to specific controllers using annotations but couldn't find a solution in stackoverflow. Decided add this content to this question instead of asking a new question.
Define the annotation
NeedLogin.class
package com.example.helloSpringBoot.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedLogin {
}
Then define the inceptor class
package com.example.helloSpringBoot.config;
import com.example.helloSpringBoot.annotation.NeedLogin;
import com.example.helloSpringBoot.util.WxUserInfoContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Logon interceptor
*
* @Author: Java Fragment
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {
//This method is executed before accessing the interface. We only need to write the business logic to verify the login status here to verify the login status before the user calls the specified interface.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
if (null == needLogin) {
needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass()
.getAnnotation(NeedLogin.class);
}
// Check login if you have login validation annotations
if (null != needLogin) {
WxUserInfoContext curUserContext = (WxUserInfoContext) request.getSession()
.getAttribute("curUserContext");
//If session No, not logged in.
if (null == curUserContext) {
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Not logged in!");
return false;
}
}
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
Then add the inceptor into the WebConfig
package com.example.helloSpringBoot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebConfig
*
* @Author: Java Fragment
*
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Custom interceptor, add intercept path and exclude intercept path
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}
Finally you are free to use the new interceptor using the new annotation @NeedLogin
package com.example.helloSpringBoot.controller;
import com.example.helloSpringBoot.annotation.NeedLogin;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
/**
* Testing does not require login
*
*
*/
@RequestMapping("/testNoLogin")
public String testNoLogin (){
return "The call is successful, this interface does not need login validation!-Java Broken read!";
}
/**
* Testing requires login
*
*
*/
@NeedLogin
@RequestMapping("/testNeedLogin")
public String testNeedLogin (){
return "testNeedLogin!";
}
}
HandlerInterceptor
successfully. It is working fine. Only the problem is, someinternal HandlerInterceptor
throws an exception before it is handled by thecustom HandlerInterceptor
. TheafterCompletion()
method which is overridden is called after the error is thrown by the internal implementation of HandlerInterceptor. Do you have solution for this? – Chetan Oswal