我知道这个问题已经问了很多遍,但是没有一个可以使我的代码正常工作。我可能做错了什么,但找不到。
我将Spring Boot与AngularJS结合使用,我想做的是预处理所有请求。
这是我的代码:
控制器:
@RestController
@RequestMapping(value = { "/user" })
public class UserController {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String getLanguage() {
return "user";
}
}
拦截器:
@Component
public class RequestHandler extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
System.out.println("intercepted");
return false;
}
}
WebConfig:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
HandlerInterceptor requestHandler;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestHandler);
}
}
并将其添加到applicationContext.xml中:
<mvc:interceptors>
<bean class="server.RequestHandler" />
</mvc:interceptors>
我整个周末都在努力使这项工作成功,但是我不能,任何帮助将不胜感激!
谢谢!
最佳答案
您可以尝试手动定义Bean
,而无需像下面这样将Interceptor
声明为@Component
:
RequestHandler.java
public class RequestHandler extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws ServletException {
System.out.println("intercepted");
return true;
}
}
WebConfig.java
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public RequestHandler requestHandler() {
return new RequestHandler();
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(requestHandler());
}
}
顺便说一句:如果将该类声明为拦截器,为什么不将其重命名为包含术语Interceptor的内容,例如
RequestInterceptor
?它应该直接工作。请让我知道这是否对您有用!
更新:我已经在原型中实现了这一点。请参阅此最小,完整且可验证的示例。希望能帮助到你!
https://github.com/dbubenheim/stackoverflow-41794738.git