org.springframework.web.servlet.view.json.MappingJackson2JsonView Java Examples
The following examples show how to use
org.springframework.web.servlet.view.json.MappingJackson2JsonView.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelController.java From PedestrianDetectionSystem with Apache License 2.0 | 6 votes |
@RequestMapping(value = "get_channel", method = RequestMethod.GET) public @ResponseBody ModelAndView getChannel(HttpSession session, HttpServletRequest request){ ServletContext context = session.getServletContext(); Integer subFlag = (Integer)request.getSession().getAttribute("sub_flag"); if(subFlag == null){ session.setAttribute("sub_flag", 1); context.setAttribute("onlineCount", (Integer)context.getAttribute("onlineCount") - 1); } Map<String, Object> result = new HashMap(); result.put("msg", "success"); result.put("rst", 0); Integer channel = (Integer) context.getAttribute("use_channel"); if (channel == null){ channel = 0; } result.put("data", channel); return new ModelAndView(new MappingJackson2JsonView(), result); }
Example #2
Source File: RestExceptionHandler.java From proxyee-down with Apache License 2.0 | 6 votes |
@Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { 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; }
Example #3
Source File: ExceptionHandler.java From yfs with Apache License 2.0 | 6 votes |
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); MappingJackson2JsonView view = new MappingJackson2JsonView(); Map<String, Object> attributes = new HashMap(); if (ex instanceof MaxUploadSizeExceededException) { attributes.put("code", ResultCode.C403.code); attributes.put("msg", "Maximum upload size of " + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + " bytes exceeded"); logger.warn(ex.getMessage()); } else { attributes.put("code", ResultCode.C500.code); attributes.put("msg", ResultCode.C500.desc); logger.error("Internal server error", ex); } view.setAttributesMap(attributes); mv.setView(view); return mv; }
Example #4
Source File: DispatcherServletConfiguration.java From activiti6-boot2 with Apache License 2.0 | 6 votes |
@Bean public ViewResolver contentNegotiatingViewResolver() { log.debug("Configuring the ContentNegotiatingViewResolver"); ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver(); List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); 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<View>(); defaultViews.add(new MappingJackson2JsonView()); viewResolver.setDefaultViews(defaultViews); return viewResolver; }
Example #5
Source File: ExceptionResolver.java From xmanager with Apache License 2.0 | 6 votes |
@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()); }
Example #6
Source File: ScheduleMethodHandlerAdapter.java From seppb with MIT License | 6 votes |
/** * 调用HandlerMethod方法,并返回json视图 * @param request * @param response * @param handlerMethod * @return */ @Override protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) { Map<String, Object> data = Maps.newHashMap(); data.put("service", handlerMethod.getBeanType().getSimpleName()); data.put("method", handlerMethod.getMethod().getName()); Stopwatch stopwatch = Stopwatch.createStarted(); try { // 调用HandleMethod方法 handlerMethod.getMethod().invoke(handlerMethod.getBean()); stopwatch.stop(); data.put("result", "success"); }catch (Exception e){ data.put("result", "error"); data.put("exception", e.toString()); }finally { data.put("cost", stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms"); } // 返回Json视图 return new ModelAndView(new MappingJackson2JsonView(), data); }
Example #7
Source File: WebAppConfig.java From tinker-manager with Apache License 2.0 | 6 votes |
@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); }
Example #8
Source File: ViewResolverRegistryTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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()); }
Example #9
Source File: BladeErrorController.java From blade-tool with GNU Lesser General Public License v3.0 | 5 votes |
@Override public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); response.setStatus(status.value()); MappingJackson2JsonView view = new MappingJackson2JsonView(); view.setObjectMapper(JsonUtil.getInstance()); view.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); return new ModelAndView(view, body); }
Example #10
Source File: ExceptionReslover.java From mmall20180107 with Apache License 2.0 | 5 votes |
@Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { logger.info(httpServletRequest.getRequestURI()+"Exception:",e); ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView()); modelAndView.addObject("status",Const.ResponseCode.ERROR); modelAndView.addObject("msg","接口异常,详情请查看日志中的异常信息"); modelAndView.addObject("data",e.toString()); return modelAndView; }
Example #11
Source File: RequestResponseBodyMethodProcessorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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); }
Example #12
Source File: MolgenisRControllerTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@BeforeEach void beforeTest() { MolgenisRController controller = new MolgenisRController(); mockMvc = MockMvcBuilders.standaloneSetup(controller) // use a json view to easily test the model values that get set .setSingleView(new MappingJackson2JsonView()) .setCustomArgumentResolvers(new TokenExtractor()) .build(); }
Example #13
Source File: ViewResolverRegistryTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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); }
Example #14
Source File: ViewResolutionTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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")); }
Example #15
Source File: ViewResolutionTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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"))); }
Example #16
Source File: SpringApiExceptionHandlerUtils.java From backstopper with Apache License 2.0 | 5 votes |
/** * 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; }
Example #17
Source File: SpringUnhandledExceptionHandlerTest.java From backstopper with Apache License 2.0 | 5 votes |
@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); }
Example #18
Source File: JsonObjectUtils.java From disconf with Apache License 2.0 | 5 votes |
/** */ public static ModelAndView JsonObjectError2ModelView(JsonObjectError json) { ModelAndView model = new ModelAndView(new MappingJackson2JsonView()); model.addObject(FrontEndInterfaceConstant.RETURN_SUCCESS, json.getSuccess()); model.addObject(FrontEndInterfaceConstant.RETURN_MESSAGE, json.getMessage()); model.addObject(FrontEndInterfaceConstant.STATUS_CODE_STRING, json.getStatus()); model.addObject(FrontEndInterfaceConstant.SESSION_ID, json.getSessionId()); return model; }
Example #19
Source File: JsonObjectUtils.java From disconf with Apache License 2.0 | 5 votes |
/** */ public static ModelAndView JsonObjectError2ModelView(JsonObjectError json) { ModelAndView model = new ModelAndView(new MappingJackson2JsonView()); model.addObject(FrontEndInterfaceConstant.RETURN_SUCCESS, json.getSuccess()); model.addObject(FrontEndInterfaceConstant.RETURN_MESSAGE, json.getMessage()); model.addObject(FrontEndInterfaceConstant.STATUS_CODE_STRING, json.getStatus()); model.addObject(FrontEndInterfaceConstant.SESSION_ID, json.getSessionId()); return model; }
Example #20
Source File: GlobalExceptionHandler.java From SENS with GNU General Public License v3.0 | 5 votes |
/** * 获取其它异常。包括500 * * @param e * @return * @throws Exception */ @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e, Model model) throws IOException { e.printStackTrace(); if (isAjax(request)) { ModelAndView mav = new ModelAndView(); MappingJackson2JsonView view = new MappingJackson2JsonView(); Map<String, Object> attributes = new HashMap<String, Object>(); if (e instanceof UnauthorizedException) { attributes.put("msg", "没有权限"); } else { attributes.put("msg", e.getMessage()); } attributes.put("code", "0"); view.setAttributesMap(attributes); mav.setView(view); return mav; } if (e instanceof UnauthorizedException) { //请登录 log.error("无权访问", e); return new ModelAndView("common/error/403"); } //其他异常 String message = e.getMessage(); model.addAttribute("code", 500); model.addAttribute("message", message); return new ModelAndView("common/error/500"); }
Example #21
Source File: ViewRenderSubtypeTest.java From apm-agent-java with Apache License 2.0 | 5 votes |
@Test void testGetUnknownSubtypes() { assertThat(getSubtype(GroovyMarkupView.class.getName())).isEqualTo("GroovyMarkup"); assertThat(getSubtype(FreeMarkerView.class.getName())).isEqualTo("FreeMarker"); assertThat(getSubtype(MappingJackson2JsonView.class.getName())).isEqualTo("MappingJackson2Json"); assertThat(getSubtype(JadeView.class.getName())).isEqualTo("Jade"); assertThat(getSubtype(InternalResourceView.class.getName())).isEqualTo("InternalResource"); assertThat(getSubtype(ThymeleafView.class.getName())).isEqualTo("Thymeleaf"); }
Example #22
Source File: RequestResponseBodyMethodProcessorTests.java From spring-analysis-note with MIT License | 5 votes |
@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<>(bean, HttpStatus.OK); }
Example #23
Source File: ViewResolverRegistryTests.java From spring-analysis-note with MIT License | 5 votes |
@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()); }
Example #24
Source File: ViewResolverRegistryTests.java From spring-analysis-note with MIT License | 5 votes |
@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); }
Example #25
Source File: ViewResolutionTests.java From spring-analysis-note with MIT License | 5 votes |
@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")); }
Example #26
Source File: RequestResponseBodyMethodProcessorTests.java From java-technology-stack with MIT License | 5 votes |
@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<>(bean, HttpStatus.OK); }
Example #27
Source File: ViewResolverRegistryTests.java From java-technology-stack with MIT License | 5 votes |
@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()); }
Example #28
Source File: ViewResolverRegistryTests.java From java-technology-stack with MIT License | 5 votes |
@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); }
Example #29
Source File: ViewResolutionTests.java From java-technology-stack with MIT License | 5 votes |
@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")); }
Example #30
Source File: ChannelController.java From PedestrianDetectionSystem with Apache License 2.0 | 5 votes |
@RequestMapping(value = "set_channel", method = RequestMethod.GET) public @ResponseBody ModelAndView setChannel(@RequestParam("use_channel")Integer channel, HttpSession session){ ServletContext context = session.getServletContext(); Map<String, Object> result = new HashMap(); result.put("msg", "success"); result.put("rst", 0); result.put("data", channel); context.setAttribute("use_channel", channel); return new ModelAndView(new MappingJackson2JsonView(), result); }