0
因此,我正在学习Spring MVC框架,并使用MappingJackson2JsonView类设置了内容协商,因此当我转到/ products时,我会得到正常的HTML视图当我去到/producs.json时,我得到了一个模型的JSON - 这很好。 我的问题是,我如何从JSON输出中排除变量?我希望排除的这些变量是由我创建的一个Interceptor来设置的,以便将属性添加到我向HTML用户显示的模型中;杰克逊JSON视图 - 从输出中排除视图变量(Spring MBV)
拦截:
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
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;
}
任何帮助,将不胜感激。