配置Spring支持自动json格式数据转换

从|Spring3.1之后,开始推荐使用RequestMappingHandlerMapping和RequestMappingHandlerAdapter来进行方法映射,

在controller里支持使用@RequestBody注解 (从2.5开始应该就支持的)

要使用Spring提供的自动将requestbody里的json字符串的entity 转换为对应的对象实例,

需要增加messageconverter,默认没有MappingJackson2HttpMessageConverter

-servlet.xml 配置:

	
	
	
	
		
			
				
			
		
	

并添加依赖的包:

jackson-annotations-2.0.5.jar

jackson-databind-2.0.5.jar

jackson-core-2.0.5.jar

下载地址:http://wiki.fasterxml.com/JacksonDownload

以上是jackson最新的三个包,一个不能少,原来的1.x版本只有两个包 (如:jackson-core-asl-1.5.6.jar      jackson-mapper-asl-1.5.6.jar


Controller里面的方法:

    @RequestMapping(value = "/db/addUser.do", method = RequestMethod.POST)
    @ResponseBody
    public String addUser(@RequestBody User user) {
        log.info(user.toString());
        return "success";
    }


用apache的 HttpClient包测试:
        HttpPost post = new HttpPost(URL);
        // 向服务器写json
        StringEntity se = new StringEntity(user, Consts.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, Consts.UTF_8.toString()));
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        post.setEntity(se);
        // post.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
        DefaultHttpClient client = new DefaultHttpClient();

        try {
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine().toString());

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            post.abort();
        } catch (IOException e) {
            e.printStackTrace();
            post.abort();
        }

你可能感兴趣的:(j2ee,spring,spring,json,encoding,user,mvc,apache)