您现在的位置:首页 >> 前端 >> 内容

springMVC接收JSON数据转java对象以及Java对象转JSON数据

时间:2017/4/11 9:24:00 点击:

  核心提示:springMVC接收JSON数据转java对象以及Java对象转JSON数据:今天开始写实训课上的一个项目,使用的是SSM框架。今天写好了登录界面的ajax数据发送,以及登录验证码功能,使用的是bo...

springMVC接收JSON数据转java对象以及Java对象转JSON数据:今天开始写实训课上的一个项目,使用的是SSM框架。今天写好了登录界面的ajax数据发送,以及登录验证码功能,使用的是bootstrap,验证使用的是Jquery.validator.js。

先贴出spring-mvc.xml

 





	

	 

      
          
        jsp">  
    

	
	
	
	


java部分

 

 

@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	public static String safecode=null;
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		return "Index";
	}
	@RequestMapping(value = "/makeCerPic", method = RequestMethod.GET)
	public String getpic(Locale locale, Model model) {
		logger.info("getpic");
		
		return "makeCerPic";
	}
	@RequestMapping(value = "/getsafecode", method = RequestMethod.GET)
	public @ResponseBody String getsafecode(){
		return safecode;
	}
	
	@RequestMapping(value = "/testreq", method = RequestMethod.POST)
	//@RequestBody UserInfo usr
	public @ResponseBody UserInfo testfoo(@RequestBody UserInfo usr){
		return usr;
	}
}
其中最后一个是我用来接收json数据的方法

 

ajax提交部分

 

function post(user,methodURL,method) {
	$.ajax({
		cache:true,
		type:method,
		datatype:"json",
		contentType: "application/json",
		url:methodURL,
		data:JSON.stringify(user),
		error: function(XMLHttpRequest,textStatus,errorThrown) {
			alert(alert(XMLHttpRequest.status+"\r\n"+XMLHttpRequest.readyState+"\r\n"+textStatus))
		},
		success: function(data,textStatus) {
			console.log(data);
			console.log(textStatus);
		}
	}

 

测试用的数据模型

 

public class UserInfo {
	public String username;
	public String password;
	

	
	public UserInfo() {
		super();
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

理一下:

 

1、数据模型类不要写带参构造函数,如果写了带参构造函数,那么一定要再写一个无参的构造函数

否则你会看到类似这个错误

WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: No suitable constructor found for type [simple type, class com.project.model.UserInfo]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@f5034a4; line: 1, column: 2]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.project.model.UserInfo]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@f5034a4; line: 1, column: 2]

2、发送数据的时候使用ajax以POST的方法发送,使用GET会出现400 Bad request或415 unsupported media等等,我都被这个错误信息搞的晕头转向,一直以为是xml里面转换器配错了

3、在spring-mvc.xml中如果没有特殊的什么转换要求用就好了,方便快捷。

4、然后SpringMVC就会自动的将json转java对象或java对象转json

5、输出java对象到前端的时候用@ResponseBody,接收前端json的时候用@RequestBody

另外,这个登录界面的验证码功能使用了这个博主的代码,贴一下他的那篇博文的地址,表示感谢

但是我发现他随机生成的验证码字符串是写入java的Httpsession的,在主页面无法通过Jquery去获取到,我想到了一个方法,在生成验证码后,将验证码字符串HomeController类中的静态变量里,就是上方

public static String safecode=null;
然后在用户输入验证码的时候用ajax GET方法去获取这个值,这样就能进行验证码的比对了

 

就是这个方法

@RequestMapping(value = "/getsafecode", method = RequestMethod.GET)
	public @ResponseBody String getsafecode(){
		return safecode;
	}

 


 

Tags:SP PR RI IN 
作者:网络 来源:不详