您的位置:首页 > 编程语言 > Java开发

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

2017-04-07 22:33 295 查看
今天开始写实训课上的一个项目,使用的是SSM框架。今天写好了登录界面的ajax数据发送,以及登录验证码功能,使用的是bootstrap,验证使用的是Jquery.validator.js。当写到使用ajax发送json格式的数据到springMVC的时候发现总是遇到400 bad request的界面,看了很多博客,stackoverflow上也看了好一些,都没能解决,找了6个小时后,经过N多尝试,终于发现了最最最最最最最根本的原因,发送参数的时候用POST就没有问题(之前一直用GET方法,然后一直在改xml里面的转换器的配置,难怪搞不定)。

先贴出spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
<mvc:annotation-driven />

<mvc:resources mapping="/resources/**" location="/resources/" />

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.project.rentweb" />

</beans:beans>


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中如果没有特殊的什么转换要求用<mvc:annotation-driven />就好了,方便快捷。

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

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

另外,这个登录界面的验证码功能使用了这个博主的代码,贴一下他的那篇博文的地址,表示感谢   http://blog.csdn.net/sanluo11/article/details/54407956

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

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

就是这个方法

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


--------4月10号补充---------

有种情况用Tomcat发布后在发布目录中能看到项目,但是还是出现404错误,这个时候可以双击



将箭头所指的值改为webapps,之前是wtpwebapps,要修改这个值要求是没有项目部署到tomcat上,所以修改前先将项目移除部署。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax spring mvc json
相关文章推荐