3 回答

TA貢獻1789條經驗 獲得超8個贊
您可以為此添加攔截器
樣本攔截器
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貢獻1779條經驗 獲得超6個贊
也許一個不錯的選擇是實現一個自定義過濾器,該過濾器在每次收到請求時運行。
您需要擴展“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 注冊過濾器之后。如果你有 Spring 安全,你需要在安全過濾器之后添加你的過濾器。

TA貢獻1780條經驗 獲得超4個贊
Spring Aspect 也是在控制器之前執行代碼的好選擇。
@Component
@Aspect
public class TestAspect {
@Before("execution(* com.test.myMethod(..)))")
public void doSomethingBefore(JoinPoint jp) throws Exception {
//code
}
}
這里myMethod()將在控制器之前執行。
添加回答
舉報