因此,我正在学习Spring MVC框架,并使用MappingJackson2JsonView类设置了内容协商,这样当我转到/products时,我会得到普通的HTML视图,当我转到/producs.json时,我会得到模型的JSON -这很好用。我的问题是,如何从JSON输出中排除变量?我希望排除的这些变量是由我创建的拦截器设置的,该拦截器为我显示给HTML用户的模型添加属性;
拦截器:
public class GlobalVariablesInterceptor extends HandlerInterceptorAdapter {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
ModelMap model = modelAndView.getModelMap();
model.addAttribute("cp", request.getServletContext().getContextPath());
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
Set<String> roles = auth.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toSet());
String userRoles = String.join(",", roles);
model.addAttribute("roles", userRoles);
model.addAttribute("authUsername", auth.getName());
}
}
}
}JSON Bean:
@Bean
public MappingJackson2JsonView jsonView() {
MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
jsonView.setPrettyPrint(true);
return jsonView;
}
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
ArrayList<View> views = new ArrayList<>();
views.add(jsonView());
views.add(xmlView());
resolver.setDefaultViews(views);
return resolver;
}任何帮助都将不胜感激。
发布于 2017-08-17 01:21:58
所以,为了将来阅读这篇文章的任何人的利益...
我尝试过的事情:
唯一起作用的事情(但显然不是很“有弹性”的代码)……查询postHandle方法的HttpServletRequest对象,查看请求的URL是否包含.json (这是JSON视图的触发器)...如果是,那么不要一开始就将这些额外的变量添加到模型中:
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
String url = request.getRequestURI().toLowerCase();
if (!(url.contains(".json") || url.contains(".xml"))) {
ModelMap model = modelAndView.getModelMap();
model.addAttribute("cp", request.getServletContext().getContextPath());
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
Set<String> roles = auth.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toSet());
String userRoles = String.join(",", roles);
model.addAttribute("roles", userRoles);
model.addAttribute("authUsername", auth.getName());
}
}
}
}https://stackoverflow.com/questions/45697511
复制相似问题