自定义HttpMessageConverter接受JSON格式的数

 1.配置修改



        
    
    
	
    
	
    
    	
        
        	
        	
    		
    		
    		
            
            
                
                
                    
                        
                        text/html;charset=UTF-8
                        application/json;charset=UTF-8
                    
                
            
        
    
    
    
      
        
        
            /WEB-INF/content/
        
        
        
            .jsp
        
    

 注:以上的配置文件和和之前的配置文件重点的区别在于,之前使用的是Spring中默认的Mapping-Jackson2HttpMessageConverter,这样只需要配置默认的就可以了。而现在使用了第三方的fastjson处理json数据,则需要另行配置HttpMessageConverter。

2.前端

 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




测试接收JSON格式的数据





编号:
书名:
作者:

3.后端

 Book.java

package com.bean;

import java.io.Serializable;

public class Book implements Serializable {
	private Integer id;
	private String name;
	private String author;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
	}
	
}

BookController.java

package com.control;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.bean.Book;

@Controller
@RequestMapping("/json")
public class BookController {
	private static final Log logger = LogFactory.getLog(BookController.class);
	
	// @RequestBody根据json数据,转换成对应的Object
    @RequestMapping(value="/testRequestBody")
    public void setJson(@RequestBody Book book,HttpServletResponse response) throws Exception{
    	// JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。
    	// 使用JSONObject将book对象转换成json输出
    	logger.info(JSONObject.toJSONString(book));
    	book.setAuthor("海哥");
    	response.setContentType("text/html;charset=UTF-8");
    	// 将book对象转换成json写出到客户端
    	response.getWriter().println(JSONObject.toJSONString(book));
    }
}

4.截图


你可能感兴趣的:(自定义HttpMessageConverter接受JSON格式的数)