Java 类org.springframework.web.servlet.view.json.MappingJackson2JsonView 实例源码

项目:devops-cstack    文件:CloudUnitApplicationContext.java   
@Bean
public ViewResolver contentNegotiatingViewResolver() {
    logger.debug("Configuring the ContentNegotiatingViewResolver");
    ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
    List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();

    UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
    urlBasedViewResolver.setViewClass(JstlView.class);
    urlBasedViewResolver.setSuffix(".html");
    viewResolvers.add(urlBasedViewResolver);

    viewResolver.setViewResolvers(viewResolvers);

    List<View> defaultViews = new ArrayList<View>();
    defaultViews.add(new MappingJackson2JsonView());
    viewResolver.setDefaultViews(defaultViews);

    return viewResolver;
}
项目:xmanager    文件:ExceptionResolver.java   
@Override
    public ModelAndView resolveException(HttpServletRequest request,
         HttpServletResponse response, Object handler, Exception e) {
        // log记录异常
        LOGGER.error(e.getMessage(), e);
        // 非控制器请求照成的异常
        if (!(handler instanceof HandlerMethod)) {
            return new ModelAndView("error/500");
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        if (WebUtils.isAjax(handlerMethod)) {
            Result result = new Result();
            result.setMsg(e.getMessage());
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.setObjectMapper(jacksonObjectMapper);
            view.setContentType("text/html;charset=UTF-8");
            return new ModelAndView(view, BeanUtils.toMap(result));
        }

        // 页面指定状态为500,便于上层的resion或者nginx的500页面跳转,由于error/500不适合对用户展示
//      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return new ModelAndView("error/500").addObject("error", e.getMessage());
    }
项目:proxyee-down    文件:RestExceptionHandler.java   
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse, Object o, Exception e) {
  HttpDownServer.LOGGER.error("rest error:",e);
  ModelAndView modelAndView = new ModelAndView();
  try {
    ResultInfo resultInfo = new ResultInfo().setStatus(ResultStatus.ERROR.getCode())
        .setMsg(ResultInfo.MSG_ERROR);
    Map<String, Object> attr = JSON.parseObject(JSON.toJSONString(resultInfo), Map.class);
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setAttributesMap(attr);
    modelAndView.setView(view);
  } catch (Exception e1) {
    e1.printStackTrace();
  }
  return modelAndView;
}
项目:tinker-manager    文件:WebAppConfig.java   
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
    e.printStackTrace();
    String messageStr = null;
    if (e instanceof BizException) {
        BizException bz = (BizException) e;
        messageStr = bz.getMessage();
    }

    if (messageStr == null || messageStr.trim().length() == 0) {
        messageStr = "系统异常";
    }

    RestResponse restR = new RestResponse();
    restR.setCode(-1);
    restR.setMessage(messageStr);
    if (HttpRequestUtils.isAjax(request)) {
        Map model = BeanMapConvertUtil.convertBean2Map(restR);
        if (logger.isInfoEnabled()) {
            logger.info(">>>>>resolveException ajax model: " + model);
        }
        return new ModelAndView(new MappingJackson2JsonView(), model);
    }

    return new ModelAndView("500", "restR", restR);
}
项目:enterkey-framework    文件:Application.java   
@Bean
public ViewResolver viewResolver() {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();

    List<View> defaultViews = new ArrayList<View>();
    defaultViews.add(new MappingJackson2JsonView());
    resolver.setDefaultViews(defaultViews);
    resolver.setOrder(0);

    List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();
    InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
    internalResourceViewResolver.setPrefix("/WEB-INF/view/");
    internalResourceViewResolver.setSuffix(".jsp");
    internalResourceViewResolver.setOrder(1);
    viewResolvers.add(internalResourceViewResolver);
    resolver.setViewResolvers(viewResolvers);

    return resolver;
}
项目:flowable-engine    文件:DispatcherServletConfiguration.java   
@Bean
public ViewResolver contentNegotiatingViewResolver() {
    LOGGER.debug("Configuring the ContentNegotiatingViewResolver");
    ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
    List<ViewResolver> viewResolvers = new ArrayList<>();

    UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
    urlBasedViewResolver.setViewClass(JstlView.class);
    urlBasedViewResolver.setPrefix("/WEB-INF/pages/");
    urlBasedViewResolver.setSuffix(".jsp");
    viewResolvers.add(urlBasedViewResolver);

    viewResolver.setViewResolvers(viewResolvers);

    List<View> defaultViews = new ArrayList<>();
    defaultViews.add(new MappingJackson2JsonView());
    viewResolver.setDefaultViews(defaultViews);

    return viewResolver;
}
项目:springboot-shiro-cas-mybatis    文件:Cas30JsonResponseView.java   
private static MappingJackson2JsonView createDelegatedView() {
    final MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setPrettyPrint(true);
    view.setDisableCaching(true);
    view.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return view;
}
项目:cas-5.1.0    文件:OidcCallbackAuthorizeViewResolver.java   
@Override
public ModelAndView resolve(final J2EContext ctx, final ProfileManager manager, final String url) {
    final Set<String> prompt = authorizationRequestSupport.getOidcPromptFromAuthorizationRequest(url);
    if (prompt.contains(OidcConstants.PROMPT_NONE)) {
        if (manager.get(true) != null) {
            return new ModelAndView(url);
        }
        final Map<String, String> model = new HashMap<>();
        model.put(OAuth20Constants.ERROR, OidcConstants.LOGIN_REQUIRED);
        return new ModelAndView(new MappingJackson2JsonView(), model);
    }
    return new ModelAndView(new RedirectView(url));
}
项目:cas-5.1.0    文件:Cas30JsonResponseView.java   
private static MappingJackson2JsonView createDelegatedView() {
    final MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setPrettyPrint(true);
    view.setDisableCaching(true);
    view.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).findAndRegisterModules();
    return view;
}
项目:xproject    文件:DefaultMvcHandlerExceptionResolver.java   
protected ModelAndView handle4AsyncRequest(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    ExceptionMetadata em = ModuleExceptionResolver.resolveException(ex);

    Result<Object> result = new Result<Object>();
    result.setSuccess(false);
    result.setCode(em.getCode());
    result.setMessage(em.getMessage());
    MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
    jsonView.setExtractValueFromSingleKeyModel(true);
    ModelAndView mav = new ModelAndView(jsonView);
    mav.addObject(result);
    return mav;
}
项目:graphium    文件:GlobalExceptionController.java   
private ModelAndView adaptException2MAV(Exception ex) {
    ModelAndView mav = new ModelAndView();
    mav.setView(new MappingJackson2JsonView());
    mav.addObject("exception",ex.getClass().getSimpleName());
    mav.addObject("message", ex.getMessage());
    return mav;
}
项目:TARA-Server    文件:IDCardController.java   
@GetMapping(path = {"/idcard"})
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    try {
        String encodedCertificate = request.getHeader(HEADER_SSL_CLIENT_CERT);
        Assert.hasLength(encodedCertificate, "Unable to find certificate from request");
        request.getSession().setAttribute(Constants.CERTIFICATE_SESSION_ATTRIBUTE, X509Utils.toX509Certificate(encodedCertificate));
        return new ModelAndView(new MappingJackson2JsonView(), Collections.singletonMap("ok", true));
    } catch (Exception e) {
        this.log(e);
        return new ModelAndView(new MappingJackson2JsonView(), Collections.singletonMap("ok", false));
    }
}
项目:cas-server-4.2.1    文件:Cas30JsonResponseView.java   
private static MappingJackson2JsonView createDelegatedView() {
    final MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setPrettyPrint(true);
    view.setDisableCaching(true);
    view.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return view;
}
项目:SpringMvcMavenDB    文件:MajorController.java   
@RequestMapping(value="/findAllMajors2",method=RequestMethod.GET)
@ResponseBody
public List<Major> findAllMajors2() throws JsonProcessingException
{
    List<Major> majorList=majorService1.findAllMajors();
       /** 
        * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。 
        * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。 
        * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。 
        * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。 
        * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。 
        * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。 
        */  
       ObjectMapper jasonObjMapper = new ObjectMapper();  
       String strJason=jasonObjMapper.writeValueAsString(majorList);
    //return strJason;


       //开始返回
       MappingJackson2JsonView view = new MappingJackson2JsonView();
       Map<String, Object> attributes = new HashMap<String, Object>();
       attributes.put("success", Boolean.TRUE);
       attributes.put("allCoursesList", majorList);


    ModelAndView modelAndView1=new ModelAndView();
    //set the name of view
    //view.setView("/course/showAllCourses");
    modelAndView1.setViewName("/major/showAllMajors");
    //add the object into model and view
       //view.setAttributesMap(attributes);
       //modelAndView1.setView(view);
    modelAndView1.addObject(majorList);
       return majorList;


}
项目:SSMSeedProject    文件:ExceptionHandlerController.java   
@ExceptionHandler({OptionalNotPresentException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handlerUnauthenticatedException(Exception ex, NativeWebRequest request) {
    if ((request.getHeader("accept").contains("application/json"))) {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, Serializable> attributes = new HashMap<>();
        attributes.put("error", HttpStatus.NOT_FOUND);
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        return new ModelAndView("/404");
    }
}
项目:SSMSeedProject    文件:ExceptionHandlerController.java   
/**
 * 全局Controller异常处理
 *
 * @param ex 异常
 * @return 跳转出错页面
 */
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handlerExceptionMethod(Exception ex, NativeWebRequest request) {
    if ((request.getHeader("accept").contains("application/json"))) {//如果不是异步请求
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, java.io.Serializable> attributes = new HashMap<>();
        attributes.put("error", HttpStatus.INTERNAL_SERVER_ERROR);
        if (env.getDefaultProfiles()[0].equals("development")) {
            attributes.put("MSG", ex.toString());
            attributes.put("Line", ex.getStackTrace()[0].getLineNumber());
            attributes.put("Method", ex.getStackTrace()[0].getMethodName());
        }
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        if (env.getDefaultProfiles()[0].equals("development")) {
            ModelAndView modelAndView = new ModelAndView("500");
            modelAndView.addObject("MSG", ex.toString());
            modelAndView.addObject("Line", ex.getStackTrace()[0].getLineNumber());
            modelAndView.addObject("Method", ex.getStackTrace()[0].getMethodName());
            Writer writer = new StringWriter();
            //异常输出到浏览器console
            ex.printStackTrace(new PrintWriter(writer));
            modelAndView.addObject("detailed", writer.toString());
            return modelAndView;
        } else {
            return new ModelAndView("/500");
        }
    }
}
项目:spring4-understanding    文件:RequestResponseBodyMethodProcessorTests.java   
@RequestMapping
@JsonView(MyJacksonView2.class)
public ResponseEntity<JacksonViewBean> handleResponseEntity() {
    JacksonViewBean bean = new JacksonViewBean();
    bean.setWithView1("with");
    bean.setWithView2("with");
    bean.setWithoutView("without");
    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    mav.addObject("bean", bean);
    return new ResponseEntity<JacksonViewBean>(bean, HttpStatus.OK);
}
项目:spring4-understanding    文件:ViewResolverRegistryTests.java   
@Test
public void contentNegotiation() {
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    this.registry.enableContentNegotiation(view);
    ContentNegotiatingViewResolver resolver = checkAndGetResolver(ContentNegotiatingViewResolver.class);
    assertEquals(Arrays.asList(view), resolver.getDefaultViews());
    assertEquals(Ordered.HIGHEST_PRECEDENCE, this.registry.getOrder());
}
项目:spring4-understanding    文件:ViewResolverRegistryTests.java   
@Test
public void contentNegotiationAddsDefaultViewRegistrations() {
    MappingJackson2JsonView view1 = new MappingJackson2JsonView();
    this.registry.enableContentNegotiation(view1);

    ContentNegotiatingViewResolver resolver1 = checkAndGetResolver(ContentNegotiatingViewResolver.class);
    assertEquals(Arrays.asList(view1), resolver1.getDefaultViews());

    MarshallingView view2 = new MarshallingView();
    this.registry.enableContentNegotiation(view2);

    ContentNegotiatingViewResolver resolver2 = checkAndGetResolver(ContentNegotiatingViewResolver.class);
    assertEquals(Arrays.asList(view1, view2), resolver2.getDefaultViews());
    assertSame(resolver1, resolver2);
}
项目:spring4-understanding    文件:ViewResolutionTests.java   
@Test
public void testJsonOnly() throws Exception {

    standaloneSetup(new PersonController()).setSingleView(new MappingJackson2JsonView()).build()
        .perform(get("/person/Corea"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.person.name").value("Corea"));
}
项目:spring4-understanding    文件:ViewResolutionTests.java   
@Test
public void testContentNegotiation() throws Exception {

    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(Person.class);

    List<View> viewList = new ArrayList<View>();
    viewList.add(new MappingJackson2JsonView());
    viewList.add(new MarshallingView(marshaller));

    ContentNegotiationManager manager = new ContentNegotiationManager(
            new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

    ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
    cnViewResolver.setDefaultViews(viewList);
    cnViewResolver.setContentNegotiationManager(manager);
    cnViewResolver.afterPropertiesSet();

    MockMvc mockMvc =
        standaloneSetup(new PersonController())
            .setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
            .build();

    mockMvc.perform(get("/person/Corea"))
        .andExpect(status().isOk())
        .andExpect(model().size(1))
        .andExpect(model().attributeExists("person"))
        .andExpect(forwardedUrl("person/show"));

    mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.person.name").value("Corea"));

    mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_XML))
        .andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
项目:SpringMVCSeedProject    文件:HandlerExceptionController.java   
/**
 * 无权限访问跳转
 */
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.FORBIDDEN)
public ModelAndView handlerUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
    if ((request.getHeader("accept").contains("application/json"))) {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, java.io.Serializable> attributes = new HashMap<>();
        attributes.put("error", "403");
        attributes.put("cause", HttpStatus.FORBIDDEN);
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        return new ModelAndView("../../403");
    }
}
项目:SpringMVCSeedProject    文件:HandlerExceptionController.java   
/**
 * 全局Controller异常处理
 *
 * @param ex 异常
 * @return 跳转出错页面
 */
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handlerExceptionMethod(Exception ex, NativeWebRequest request) {

    //将错误信息记录到数据库
    LogToDB(ex);

    if ((request.getHeader("accept").contains("application/json"))) {//如果不是异步请求
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, java.io.Serializable> attributes = new HashMap<>();
        attributes.put("error", "500");
        attributes.put("cause", HttpStatus.INTERNAL_SERVER_ERROR);
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        ModelAndView modelAndView = new ModelAndView("../../500");
        modelAndView.addObject("MSG", ex.toString());
        modelAndView.addObject("Line", ex.getStackTrace()[0].getLineNumber());
        modelAndView.addObject("Method", ex.getStackTrace()[0].getMethodName());
        Writer writer = new StringWriter();
        //客户端输出一下,打开F12可以看到
        ex.printStackTrace(new PrintWriter(writer));
        modelAndView.addObject("detailed", writer.toString());
        return modelAndView;
    }
}
项目:backstopper    文件:SpringApiExceptionHandlerUtils.java   
/**
 * Reusable static method for generating a ModelAndView that will be serialized to a JSON representation of the
 * DefaultErrorContractDTO.
 *
 * @return A ModelAndView that will be serialized to a JSON representation of the DefaultErrorContractDTO. (NOTE:
 * make sure the DefaultErrorContractDTO is FULLY populated before calling this method! Changes to the
 * DefaultErrorContractDTO after calling this method may not be reflected in the returned ModelAndView).
 */
public ModelAndView generateModelAndViewForErrorResponse(
    DefaultErrorContractDTO errorContractDTO, int httpStatusCode, Collection<ApiError> rawFilteredApiErrors,
    Throwable originalException, RequestInfoForLogging request
) {
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setExtractValueFromSingleKeyModel(true);
    view.setObjectMapper(getObjectMapperForJsonErrorResponseSerialization(
        errorContractDTO, httpStatusCode, rawFilteredApiErrors, originalException, request
    ));
    ModelAndView mv = new ModelAndView(view);
    mv.addObject(errorContractDTO);
    return mv;
}
项目:backstopper    文件:SpringUnhandledExceptionHandlerTest.java   
@Test
public void generateLastDitchFallbackErrorResponseInfo_returns_expected_value() throws JsonProcessingException {
    // given
    Exception ex = new Exception("kaboom");
    RequestInfoForLogging reqMock = mock(RequestInfoForLogging.class);
    String errorId = UUID.randomUUID().toString();
    Map<String, List<String>> headersMap = MapBuilder.builder("error_uid", singletonList(errorId)).build();

    ApiError expectedGenericError = testProjectApiErrors.getGenericServiceError();
    int expectedHttpStatusCode = expectedGenericError.getHttpStatusCode();
    Map<String, List<String>> expectedHeadersMap = new HashMap<>(headersMap);
    String expectedBodyPayload = JsonUtilWithDefaultErrorContractDTOSupport.writeValueAsString(
        new DefaultErrorContractDTO(errorId, singletonList(expectedGenericError))
    );

    // when
    ErrorResponseInfo<ModelAndView> response = handlerSpy
        .generateLastDitchFallbackErrorResponseInfo(ex, reqMock, errorId, headersMap);

    // then
    assertThat(response.httpStatusCode).isEqualTo(expectedHttpStatusCode);
    assertThat(response.headersToAddToResponse).isEqualTo(expectedHeadersMap);
    assertThat(response.frameworkRepresentationObj.getView()).isInstanceOf(MappingJackson2JsonView.class);
    ObjectMapper objectMapperUsed = ((MappingJackson2JsonView)response.frameworkRepresentationObj.getView()).getObjectMapper();
    assertThat(objectMapperUsed).isSameAs(JsonUtilWithDefaultErrorContractDTOSupport.DEFAULT_SMART_MAPPER);
    assertThat(response.frameworkRepresentationObj.getModel()).hasSize(1);
    Object modelObj = response.frameworkRepresentationObj.getModel().values().iterator().next();
    assertThat(modelObj).isInstanceOf(DefaultErrorContractDTO.class);
    assertThat(objectMapperUsed.writeValueAsString(modelObj)).isEqualTo(expectedBodyPayload);
}
项目:comics-blog    文件:HandlerException400Resolver.java   
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    if (ex instanceof HttpMediaTypeNotSupportedException) {
        response.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value());
        return new ModelAndView(new MappingJackson2JsonView(), "error", new RestError("Unsupported Media Type"));
    } else {
        return null;
    }
}
项目:petclinic    文件:JsonViewResolver.java   
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
  MappingJackson2JsonView view = new MappingJackson2JsonView();
  view.setExtractValueFromSingleKeyModel(true);
  view.setPrettyPrint(true);
  return view;
}
项目:vmAndSpringMVC    文件:GeneralController.java   
@ResponseBody
@RequestMapping(value = "/test.json")
public ModelAndView doJson(Model model) {
    Map<String, String> result = new HashMap<String, String>();
    result.put("test1", "test1");
    result.put("test2", "test2");

    model.addAttribute("success", true);
    model.addAttribute("result", result);
    return new ModelAndView(new MappingJackson2JsonView(), null);

}
项目:SpringMVCWithJavaConfig    文件:HandlerExceptionController.java   
/**
 * 无权限访问跳转
 */
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.FORBIDDEN)
public ModelAndView handlerUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
    if ((request.getHeader("accept").contains("application/json"))) {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, java.io.Serializable> attributes = new HashMap<>();
        attributes.put("error", "403");
        attributes.put("cause", HttpStatus.FORBIDDEN);
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        return new ModelAndView("../../403");
    }
}
项目:SpringMVCWithJavaConfig    文件:HandlerExceptionController.java   
/**
 * 全局Controller异常处理
 *
 * @param ex 异常
 * @return 跳转出错页面
 */
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handlerExceptionMethod(Exception ex, NativeWebRequest request) {

    //将错误信息记录到数据库
    LogToDB(ex);

    if ((request.getHeader("accept").contains("application/json"))) {//如果不是异步请求
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, java.io.Serializable> attributes = new HashMap<>();
        attributes.put("error", "500");
        attributes.put("cause", HttpStatus.INTERNAL_SERVER_ERROR);
        view.setAttributesMap(attributes);
        return new ModelAndView(view);
    } else {
        ModelAndView modelAndView = new ModelAndView("../../500");
        modelAndView.addObject("MSG", ex.toString());
        modelAndView.addObject("Line", ex.getStackTrace()[0].getLineNumber());
        modelAndView.addObject("Method", ex.getStackTrace()[0].getMethodName());
        Writer writer = new StringWriter();
        //客户端输出一下,打开F12可以看到
        ex.printStackTrace(new PrintWriter(writer));
        modelAndView.addObject("detailed", writer.toString());
        return modelAndView;
    }
}
项目:availability    文件:WebMvcConfig.java   
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
    mappingJackson2JsonView.setObjectMapper(objectMapper);
    registry.enableContentNegotiation(true, mappingJackson2JsonView);
    registry.viewResolver(viewResolver);
}
项目:atsy    文件:AbstractControllerTest.java   
protected UncheckedExceptionResolver uncheckedExceptionResolver() {
  MappingJackson2JsonView jsonView = new MappingJackson2JsonView(objectMapper);
  jsonView.setContentType(MediaTypes.APPLICATION_JSON_UTF8.toString());

  MessageKeyResolver messageKeyResolver = new MessageKeyResolverImpl(atsyInternalMessageSource);

  return new UncheckedExceptionResolver(jsonView, messageKeyResolver);
}
项目:spring-portlet-sample    文件:BooksController.java   
@ResourceMapping("json")
public ModelAndView listBooksJson() {
    ModelAndView mav = new ModelAndView();
    mav.addObject("books", bookService.getAllBooks());
    mav.setView(new MappingJackson2JsonView());
    return mav;
}
项目:fengduo    文件:ItemController.java   
private ModelAndView createJsonMav(boolean isSuccess, Long code, String info) {
    ModelAndView mav = new ModelAndView();
    mav.setView(new MappingJackson2JsonView());
    mav.addObject("isSuccess", isSuccess);
    mav.addObject("code", code);
    mav.addObject("info", info);
    return mav;
}
项目:fengduo    文件:ComponentController.java   
protected ModelAndView createFileJsonMav(ResultCode code, String msg,
        String object) {
    ModelAndView mav = new ModelAndView();
    mav.setView(new MappingJackson2JsonView());
    mav.addObject("code", code.value);
    mav.addObject("message", msg);
    mav.addObject("file_path", object);// 富文本编辑器返回的参数
    mav.addObject("url", object == null ? StringUtils.EMPTY : object);
    return mav;
}
项目:fengduo    文件:ComponentController.java   
protected ModelAndView createJsonMav(String msg, ResultCode code,
        Object object) {
    ModelAndView mav = new ModelAndView();
    mav.setView(new MappingJackson2JsonView());
    mav.addObject("code", Integer.toString(code.value));
    mav.addObject("message", msg);
    mav.addObject("data", object == null ? StringUtils.EMPTY : object);
    return mav;
}
项目:mcs    文件:MatchmakerCloudSearchConfiguration.java   
@Bean
public ViewResolver viewResolver() {
  return new ViewResolver() {
    public View resolveViewName(String viewName, Locale locale) throws Exception {
      return new MappingJackson2JsonView();
    }
  };
}
项目:pinenut    文件:JsonViewResolver.java   
/**
 * Get the view to use.
 *
 * @return Always returns an instance of {@link MappingJackson2JsonView}.
 */
@Override
public View resolveViewName(String viewName, Locale locale)
        throws Exception {
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setPrettyPrint(true);
    return view;
}
项目:pinenut    文件:JsonViewResolver.java   
/**
 * Get the view to use.
 *
 * @return Always returns an instance of {@link MappingJackson2JsonView}.
 */
@Override
public View resolveViewName(String viewName, Locale locale)
        throws Exception {
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setPrettyPrint(true);
    return view;
}
项目:javase-study    文件:ResponseMessage.java   
/**
 * 根据SystemException返回视图
 *
 * @param e SystemException
 * @return 视图
 */
public static ModelAndView asModelAndView(SystemException e) {
    MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
    jsonView.setExtractValueFromSingleKeyModel(true);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", e.getErrorCode().getNumber());
    if (e.getMessage() != null) {
        map.put("message", e.getMessage());
    } else {
        map.put("message", "System Error");
    }
    map.put("exMessage", e.getPropertyMap());
    return new ModelAndView(jsonView, map);
}