3 回答
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以為此添加攔截器
樣本攔截器
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response) {
//Add Login here
return true;
}
}
配置
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
}
}
希望這可以幫助
TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
也許一個(gè)不錯(cuò)的選擇是實(shí)現(xiàn)一個(gè)自定義過(guò)濾器,該過(guò)濾器在每次收到請(qǐng)求時(shí)運(yùn)行。
您需要擴(kuò)展“OncePerRequestFilter”并覆蓋方法“doFilterInternal”
public class CustomFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
//Add attributes to request
request.getSession().setAttribute("attrName", new String("myValue"));
// Run the method requested by petition
filterChain.doFilter(request, response);
//Do something after method runs if you need.
}
}
在您必須在 Spring 中使用 FilterRegistrationBean 注冊(cè)過(guò)濾器之后。如果你有 Spring 安全,你需要在安全過(guò)濾器之后添加你的過(guò)濾器。
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
Spring Aspect 也是在控制器之前執(zhí)行代碼的好選擇。
@Component
@Aspect
public class TestAspect {
@Before("execution(* com.test.myMethod(..)))")
public void doSomethingBefore(JoinPoint jp) throws Exception {
//code
}
}
這里myMethod()將在控制器之前執(zhí)行。
添加回答
舉報(bào)
