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

项目:onboard    文件:ExceptionHandler.java   
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {
    ModelAndView mav = super.doResolveException(request, response, handler, ex);

    if (ex instanceof NoPermissionException) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        logger.info(String.valueOf(response.getStatus()));
    } else if (ex instanceof BadRequestException) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
    } else if (ex instanceof NoLoginException) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else if (ex instanceof ResourceNotFoundException || ex instanceof InvitationTokenExpiredException
            || ex instanceof InvitationTokenInvalidException || ex instanceof RegisterTokenInvalidException
            || ex instanceof ResetPasswordTokenInvalidException) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
    } else {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

    mav.setView(new MappingJacksonJsonView());
    mav.addObject("exception", ex);
    logger.debug("view name = {}", mav.getViewName());

    return mav;
}
项目:class-guard    文件:ViewResolutionTests.java   
@Test
public void testJsonOnly() throws Exception {

    standaloneSetup(new PersonController()).setSingleView(new MappingJacksonJsonView()).build()
        .perform(get("/person/Corea"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.person.name").value("Corea"));
}
项目:class-guard    文件: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 MappingJacksonJsonView());
    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")));
}
项目:maven-framework-project    文件:WebMvcConfig.java   
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
    ContentNegotiatingViewResolver result = new ContentNegotiatingViewResolver();
    Map<String, String> mediaTypes = new HashMap<String, String>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
    result.setMediaTypes(mediaTypes);
    MappingJacksonJsonView jacksonView = new MappingJacksonJsonView();
    jacksonView.setExtractValueFromSingleKeyModel(true);
    Set<String> modelKeys = new HashSet<String>();
    modelKeys.add("events");
    modelKeys.add("event");
    jacksonView.setModelKeys(modelKeys);
    result.setDefaultViews(Collections.singletonList((View) jacksonView));
    return result;
}
项目:maven-framework-project    文件:WebMvcConfig.java   
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
    ContentNegotiatingViewResolver result = new ContentNegotiatingViewResolver();
    Map<String, String> mediaTypes = new HashMap<String, String>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
    result.setMediaTypes(mediaTypes);
    MappingJacksonJsonView jacksonView = new MappingJacksonJsonView();
    jacksonView.setExtractValueFromSingleKeyModel(true);
    Set<String> modelKeys = new HashSet<String>();
    modelKeys.add("events");
    modelKeys.add("event");
    jacksonView.setModelKeys(modelKeys);
    result.setDefaultViews(Collections.singletonList((View) jacksonView));
    return result;
}
项目:maven-framework-project    文件:WebMvcConfig.java   
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
    ContentNegotiatingViewResolver result = new ContentNegotiatingViewResolver();
    Map<String, String> mediaTypes = new HashMap<String, String>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
    result.setMediaTypes(mediaTypes);
    MappingJacksonJsonView jacksonView = new MappingJacksonJsonView();
    jacksonView.setExtractValueFromSingleKeyModel(true);
    Set<String> modelKeys = new HashSet<String>();
    modelKeys.add("events");
    modelKeys.add("event");
    jacksonView.setModelKeys(modelKeys);
    result.setDefaultViews(Collections.singletonList((View) jacksonView));
    return result;
}
项目:maven-framework-project    文件:WebMvcConfig.java   
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
    ContentNegotiatingViewResolver result = new ContentNegotiatingViewResolver();
    Map<String, String> mediaTypes = new HashMap<String, String>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
    result.setMediaTypes(mediaTypes);
    MappingJacksonJsonView jacksonView = new MappingJacksonJsonView();
    jacksonView.setExtractValueFromSingleKeyModel(true);
    Set<String> modelKeys = new HashSet<String>();
    modelKeys.add("events");
    modelKeys.add("event");
    jacksonView.setModelKeys(modelKeys);
    result.setDefaultViews(Collections.singletonList((View) jacksonView));
    return result;
}
项目:ds4p    文件:LegalRepresentativeController.java   
/**
 * Adds the legal representative.
 *
 * @param newLegalRepresentativeDto the new legal representative dto
 * @param result the result
 * @param response the response
 * @param model the model
 * @return the model and view
 * @throws ParseException the parse exception
 */
@RequestMapping(value="connectionMain.html", method=RequestMethod.POST)
public ModelAndView addLegalRepresentative(@Valid LegalRepresentativeDto newLegalRepresentativeDto,
        BindingResult result,
        HttpServletResponse response,
        Model model) throws ParseException {

    fieldValidator.validate(newLegalRepresentativeDto, result);
    if (result.hasErrors()) {
        MappingJacksonJsonView view = new MappingJacksonJsonView();
        Map<String, String> map = new HashMap<String, String>();

        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            for(String errorCode : error.getCodes()) {
                try {
                    String errorMessage = messageProperties.getMessage(errorCode, null, null);
                    String[] a = errorCode.split("\\.");

                    //the third token is the field name
                    map.put(a[a.length - 1], errorMessage);
                } catch(NoSuchMessageException e) {
                    continue;
                }
            }
        }

        view.setAttributesMap(map);
        ModelAndView mav = new ModelAndView();
        mav.setView(view);

        //return json if validation not pass
        return mav;
    }

    AuthenticatedUser currentUser = userContext.getCurrentUser();

    PatientProfileDto legalRepDto = patientLegalRepresentativeAssociationService.getPatientDtoFromLegalRepresentativeDto(newLegalRepresentativeDto);
    PatientLegalRepresentativeAssociationDto associationDto = patientLegalRepresentativeAssociationService.getAssociationDtoFromLegalRepresentativeDto(newLegalRepresentativeDto);

    //save to get id
    PatientProfileDto updatedLegalRepresentativeDto = patientService.savePatient(legalRepDto);
    associationDto.setPatientId(patientService.findPatientProfileByUsername(currentUser.getUsername()).getId());
    associationDto.setLegalRepresentativeId(updatedLegalRepresentativeDto.getId());
    patientLegalRepresentativeAssociationService.savePatientLegalRepresentativeAssociationDto(associationDto);

    //return html if validation passed
    return new ModelAndView("redirect:/patients/connectionMain.html");
}
项目:izzymongo    文件:ControllerException.java   
public ModelAndView asModelAndView() {
        MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
        return new ModelAndView(jsonView, ImmutableMap.of("error", message));
}