2017-08-15 50 views
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; 
} 

任何帮助,将不胜感激。

回答

0

因此,对于任何人谁在将来读取该的利益....

事情我想:

  • 设定模型变量的显式列表去 前进,在这样做WebContextConfig中的bean定义。 没有工作。
  • 查询拦截器的postHandle 方法中的ModelAndView对象;尝试查看View是否是MappingJackson2JsonView的实例 ;没有工作。
  • 查询的postHandle方法的HttpServletResponse对象以获得其 内容类型,看看它是否是应用程序/ JSON(没有工作......空 指针异常)等

一两件事,没有工作(但显然不是非常'富有弹性'的代码)....查询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()); 
      } 

     } 
    } 

}