springboot 返回结果统一大小写
时间: 2023-06-22 13:46:27 浏览: 171
可以在SpringBoot项目中配置一个返回结果统一大小写的拦截器,拦截器的实现可以参考以下示例代码:
```
public class ResultCaseInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null && modelAndView.getModelMap() != null) {
Map<String, Object> modelMap = modelAndView.getModelMap();
Map<String, Object> newModelMap = new HashMap<>();
for (Map.Entry<String, Object> entry : modelMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
newModelMap.put(key, ((String) value).toLowerCase());
} else {
newModelMap.put(key, value);
}
}
modelAndView.getModelMap().clear();
modelAndView.addAllObjects(newModelMap);
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
```
在SpringBoot项目中注册拦截器,使其生效:
```
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ResultCaseInterceptor()).addPathPatterns("/**");
}
}
```
这样,返回结果中所有的字符串都会被转换成小写。如果需要转换成大写,只需要修改拦截器中的逻辑即可。
阅读全文