所以我正在学习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;
}
任何帮助将不胜感激。
答案 0 :(得分:0)
所以,为了将来读这篇文章的人的利益....
我尝试过的事情:
一件事确实有效(但显然不是非常“弹性”的代码)....查询postHandle方法的HttpServletRequest对象,查看请求的URL是否包含.json(这是JSON视图的触发器) )...如果是,那么首先不要将这些额外的变量添加到模型中:
<div class='svg-container'>
<svg class='canvas' viewBox='0 0 10 10'>
<circle class='geometry' cx='5' cy='5'
r='2.5'/>
</svg>
</div>