? 这个接口可以自定义拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer继承了WebMvcConfigurerAdapter大部分内容。
@Configuration
public class WebMVCConfiguration implements WebMvcConfigurer {
/**
* 是否包含.*来映射请求
* 假设RequestMapping注解中指定的路径是/test
* 如果设置成True,那么对于/test.do,/test.a等任何包含.的请求都会映射到/test上去;
* 如果设置成False,那么对于这种请求不会进行映射。
*
*/
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(true);
}
}
结果:
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.add(new HandlerExceptionResolver() {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
BaseResult baseResult = new BaseResult();
if(e instanceof MissingServletRequestParameterException) {
baseResult.setCode(-1);
baseResult.setMessage("系统参数异常,请联系管理员");
}
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
try {
httpServletResponse.getWriter().write(JSON.toJSONString(baseResult));
} catch (IOException ex) {
ex.printStackTrace();
}
return new ModelAndView();
}
});
}
结果:
原文:https://www.cnblogs.com/undefined22/p/12657852.html