有人可以告诉我为什么我从Spring获得HTTP状态406

时间:2013-06-06 14:20:43

标签: json spring spring-mvc jackson

有人可以告诉我为什么我从Spring获得HTTP状态406吗?我试图让spring返回一些json代码,我恢复了406状态..

这是我的控制器代码:

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public  User getDisplayDefault(ModelMap model) {
      return new User("user name", "userid");
}

现在这是我的javaconfig:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.xxxx.mvc.web"})
public class WebMVCConfiguration extends WebMvcConfigurerAdapter
{

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfiguration.class);

    @Bean
    public ViewResolver resolver()
    {
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        url.setPrefix("/views/");
        url.setViewClass(JstlView.class);
        url.setSuffix(".jsp");
        return url;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        logger.debug("setting up resource handlers");
        registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        logger.debug("configureDefaultServletHandling");
        configurer.enable();
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver()
    {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }
}

所以我真的不明白为什么我的json没有回来

1 个答案:

答案 0 :(得分:1)

你的类路径上有Jackson / Jackson2库吗?如果不是Spring将不会创建消息转换器。来自文档:

  • MappingJackson2HttpMessageConverter(或MappingJacksonHttpMessageConverter)转换为/从JSON转换 - 如果类路径中存在Jackson 2(或Jackson),则添加。