我有一个Spring Boot应用程序,它使用SpringBootServletInitializer
。
在我的Controller
中,我有多个端点,它们根据URL中包含的参数进行区分,如下所示:
@RequestMapping(value = "myEndpoint", method = RequestMethod.GET, params = { "Id", "name", "petType" })
public void get(@RequestParam String id, @RequestParam String name, @RequestParam String petType){
//do stuff
}
@RequestMapping(value = "myEndpoint", method = RequestMethod.GET, params = { "Id", "name"})
public void get(@RequestParam String id, @RequestParam String name){
//do stuff
}
在@RequestMapping
标记中包含params意味着如果缺少params,则会向发出请求的客户端发送一个响应,告知它们自己的错误;但是,服务器端不会记录任何内容。
我想实现日志记录,所以如果向/myEndpoint
发出的请求缺少参数,那么它就会显示在服务器日志中。类似于原始请求的url和params。为此,我遇到了this spring tutorial,我试图实现它。然而,我遇到了一个问题,即教程实现了一个扩展WebApplicationInitalizer
的CustomWebAppInitializer
,但我的应用程序已经扩展了SpringBootServletInitializer
。
当我尝试实现两者时,我得到了一个错误,因为SpringBootServletInitializer
已经初始化了上下文根,所以SpringBoot已经初始化了。
当我尝试覆盖SpringBootServletInitializer
中的onStartup()
方法时,它似乎可以工作,但是我的应用程序没有正确初始化,并且不能从浏览器访问。
我尝试在调用ServletContext
之前覆盖该方法并添加一个筛选器,然后再将该方法传递回链上,但同样也不起作用。
servletContext.addFilter("CommonsRequestLoggingFilter",
CommonsRequestLoggingFilter.class)
.addMappingForServletNames(null, false, "myApp");
super.onStartup(servletContext);
我有点迷路了。我在这里做错了什么?(可能是所有内容)。
发布于 2018-04-25 20:48:43
因为Spring Boot已经设置了上下文,所以不需要使用CustomWebAppInitializer。您只需要在配置类中为CommonsRequestLoggingFilter声明一个bean。如果行为不能满足您的需要,您可以实现javax.servlet.Filter并为您的实现声明一个bean。
发布于 2018-06-10 02:12:19
尝试在您的WebMvcConfigurer上添加自定义HandlerInterceptor以用于日志记录。
@Configuration
public class HttpRequestInterceptorConfigurer implements WebMvcConfigurer {
private static Logger LOG = Logger.getLogger(HttpRequestInterceptorConfigurer.class);
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LOG.info("URI : " +request.getRequestURI() +" - QueryStr : " +request.getQueryString());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
});
}
}
https://stackoverflow.com/questions/50022159
复制相似问题