SpringMVC Controller接收前台ajax的GET或POST请求返回各种参数
这几天写新项目遇到这个问题,看这位博主总结得不错,懒得写了,直接转!原文:http://blog.csdn.net/yixiaoping/article/details/45281721原文有些小错误,加上个人比较喜欢markdown写东西,重新编排了下。
闲话少说,刚开始用SpringMVC, 页面要使用jquery的ajax请求Controller。 但总是失败,主要表现为以下两个异常为:
异常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
异常二:SpringMVC @ResponseBody 415错误处理
网上分析原因很多,但找了很久都没解决,基本是以下几类:
- springmvc添加配置、注解;
- pom.xml添加jackson包引用;
- Ajax请求时没有设置Content-Type为application/json
- 发送的请求内容不要转成JSON对象,直接发送JSON字符串即可
这些其实都没错!!!
以下是我分析的解决步骤方法:
(1)springMVC配置文件开启注解
<!-- 开启注解-->
<mvc:annotation-driven />
(2)添加springMVC需要添加如下配置。 (这个要注意spring版本,3.x和4.x配置不同)
- spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
- spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
具体可以查看spring-web的jar确认,哪个存在用哪个!
spring3.x配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-</value>
</list>
</property>
</bean>
spring4.x配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-</value>
</list>
</property>
</bean>
(3)pom.xml添加jackson依赖(这个要注意spring版本,3.x和4.x配置不同)
如果是spring 3.x,pom.xml添加如下配置
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.8.</version>
</dependency> <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.8.</version>
</dependency></span>
spring4.x, pom.xml添加如下配置
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.</version>
</dependency>
这里要说明一下,spring3.x用的是org.codehaus.jackson的1.x版本,在maven资源库,已经不在维护,统一迁移到com.fasterxml.jackson,版本对应为2.x
(4)ajax请求要求
dataType 为 json
contentType 为 ‘application/json;charse=UTF-8’
data 转JSON字符串
我的代码如下:
(注意:这里只是针对POST +JSON字符串形式请求,后面我会详细讲解不同形式请求,的处理方法和案例)
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
}
$.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data),
dataType: 'json',
contentType:'application/json;charset=UTF-8',
success : function(result) {
console.log(result);
}
});
(5) Controller 接收响应JSON
以上配置OK,Controller中使用JSON方式有多种。这里简单介绍几种。
这个关键在于ajax请求是将数据以什么形式传递到后台,这里我总结了三种形式
- POST + JSON字符串形式
- POST + JSON对象形式
- GET + 参数字符串
方式一: POST + JSON字符串形式,如下: //请求数据,登录账号 +密码
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data), //转JSON字符串
dataType: 'json',
contentType:'application/json;charset=UTF-8', //contentType很重要
success : function(result) {
console.log(result);
}
});方式二: POST + JSON对象形式,如下:
//请求数据,登录账号 +密码
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : data, //直接用JSON对象
dataType: 'json',
success : function(result) {
console.log(result);
}
});代码案例:
5-1: 使用@RequestBody来设置输入 ,@ResponseBody设置输出 (POST + JSON字符串形式)
JS请求:
//请求数据,登录账号 +密码
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data), //转JSON字符串
dataType: 'json',
contentType:'application/json;charset=UTF-8', //contentType很重要
success : function(result) {
console.log(result);
}
});Controller处理:
@RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")
@ResponseBody
public Object unlock(@RequestBody User user) {
JSONObject jsonObject = new JSONObject(); try{
Assert.notNull(user.getUserAccount(), "解锁账号为空");
Assert.notNull(user.getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
jsonObject.put("status", "success");
}catch(Exception ex){
jsonObject.put("message", ex.getMessage());
jsonObject.put("status", "error");
}
return jsonObject;
}5-2: 使用HttpEntity来实现输入绑定,来ResponseEntit输出绑定(POST + JSON字符串形式)
JS请求:
//请求数据,登录账号 +密码
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data), //转JSON字符串
dataType: 'json',
contentType:'application/json;charset=UTF-8', //contentType很重要
success : function(result) {
console.log(result);
}
});Controller处理:
@RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")
public ResponseEntity<Object> unlock(HttpEntity<User> user) {
JSONObject jsonObject = new JSONObject(); try{
Assert.notNull(user.getBody().getUserAccount(), "解锁账号为空");
Assert.notNull(user.getBody().getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getBody().getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
Assert.isTrue(StringUtils.equalsIgnoreCase(user.getBody().getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
jsonObject.put("status", "success");
}catch(Exception ex){
jsonObject.put("message", ex.getMessage());
jsonObject.put("status", "error");
}
ResponseEntity<Object> responseResult = new ResponseEntity<Object>(jsonObject,HttpStatus.OK);
return responseResult;
}5-3: 使用request.getParameter获取请求参数,响应JSON(POST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解method ,
如果不加适用GET + POST ;
如果 method= RequestMethod.POST,用于POST 请求;
如果method=RequestMethod.GET,用于GET请求;
POST+ JSON对象形式请求:
var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : data,
dataType: 'json',
success : function(result) {
console.log(result);
}
});GET + 参数字符串请求:
$.ajax({
url : ctx + "/unlock.do",
type : "GET",
dataType: "text",
data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
success : function(result) {
console.log(result);
}
});Controller处理:
@RequestMapping(value = "/unlock")
public void unlock(HttpServletRequest request,HttpServletResponse response) throws IOException {
JSONObject jsonObject = new JSONObject(); String userAccount = (String)request.getParameter("userAccount");
String userPasswd = (String)request.getParameter("userPasswd");
try{
Assert.notNull(userAccount, "解锁账号为空");
Assert.notNull(userPasswd, "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
Assert.isTrue(StringUtils.equals(userAccount,currentLoginUser.getUserAccount()), "解锁账号错误");
Assert.isTrue(StringUtils.equalsIgnoreCase(userPasswd,currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
jsonObject.put("status", "success");
}catch(Exception ex){
jsonObject.put("message", ex.getMessage());
jsonObject.put("status", "error");
} response.getWriter().print(jsonObject.toString());
}5-4: 使用@ModelAttribute将参数封装对象,响应JSON(POST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解method 。
如果不加适用GET + POST ;
如果 method= RequestMethod.POST,用于POST 请求;
如果method=RequestMethod.GET,用于GET请求;
POST+ JSON对象形式请求:var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : data,
dataType: 'json',
success : function(result) {
console.log(result);
}
});GET + 参数字符串请求:
$.ajax({
url : ctx + "/unlock.do",
type : "GET",
dataType: "text",
data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
success : function(result) {
console.log(result);
}
});Controller处理:(这个案例只支持POST)
@RequestMapping(value = "/unlock",method = RequestMethod.POST)
public void unlock(@ModelAttribute("user") User user,PrintWriter printWriter) throws IOException {
JSONObject jsonObject = new JSONObject(); try{
Assert.notNull(user.getUserAccount(), "解锁账号为空");
Assert.notNull(user.getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),cur rentLoginUser.getUserAccount()), "解锁账号错误");
Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
jsonObject.put("status", "success");
}catch(Exception ex){
jsonObject.put("message", ex.getMessage());
jsonObject.put("status", "error");
}
printWriter.print(jsonObject.toString());
}
SpringMVC Controller接收前台ajax的GET或POST请求返回各种参数的更多相关文章
- controller接收前台数据—中文乱码问题
项目用的开发环境为tomcat+eclipse+SSM 正如题目,controller接收前台数据-中文乱码问题,在页面编码为UTF-8的前提下,解决方案有二: 一) controller接收数据时, ...
- SpringMVC Controller接收参数总结
本文中Controller的开发环境如下表格所示,Maven对应POM配置如下代码段所示: 系统/工具 版本号OS Windows 7 Home BasicJava 1.7.0_79Eclipse M ...
- spring 接收前台ajax传来的参数的几个方法
知识补充 JSON.stringify(), 将value(Object,Array,String,Number...)序列化为JSON字符串JSON.parse(), 将JSON数据解析为js原生值 ...
- SpringMVC源码学习:容器初始化+MVC初始化+请求分发处理+参数解析+返回值解析+视图解析
目录 一.前言 二.初始化 1. 容器初始化 根容器查找的方法 容器创建的方法 加载配置文件信息 2. MVC的初始化 文件上传解析器 区域信息解析器 handler映射信息解析 3. Handler ...
- 【spring】spring boot中使用@EnableTransactionManagement 以后,spring mvc接收前台ajax的post方法传过来的参数,使用@RequestBody接收不到参数
在启动类上添加了注解: @EnableTransactionManagement, postMan测试接口,以这种方式传递参数: 测试结果: 接收不到参数 问题解决: 原因:是因为 这个项目中的Con ...
- springmvc Controller接收前端参数的几种方式总结
(1) 普通方式-请求参数名和Controller方法的参数一致 @Controller @RequestMapping("/param") public class TestPa ...
- SpringMVC Controller 接收页面传递的中文参数出现乱码
在Controller中接收到的POST参数如果是中文的话,显示为乱码.已知客户端传过来时编码为UTF-8. 问题产生分析: spring MVC中默认的编码格式为“ISO-8859-1”,因此造成乱 ...
- SpringMVC controller接收的中文参数乱码
CharacterEncodingFilter只对POST请求有用,GET请求的需要对你运行的tomcat 目录conf/server.xml文件中<Connector connectionTi ...
- springmvc接收前台(可以是ajax)传来的数组list,map,set等集合,复杂对象集合等图文详解
参考帖子: http://blog.csdn.net/wabiaozia/article/details/50803581 方法参考: { "token":"" ...
随机推荐
- 【论文阅读】Wing Loss for Robust Facial Landmark Localisation with Convolutional Neural Networks
Wing Loss for Robust Facial Landmark Localisation with Convolutional Neural Networks 参考 1. 人脸关键点: 2. ...
- python从零开始 -- 第0篇之Hello World!
为什么选择python以及版本选择 学习资料 学习方法和路径 1. 为什么选择python以及版本选择: Python 好玩,强大,更多关于关于为什么选择Python,在 编程小白的第一本 Pyt ...
- Python学习之路基础篇--09Python基础,初识函数
函数可以分为内置函数 和 自定义函数.这次关注的主要是自定义函数.定义函数之后,就可以在任何需要它的地方调用. 1 返回值的重要性 返回值的3种情况 没有返回值 ---- 返回None 不定 retu ...
- vue.js 精学记录
v-bind:class使用的方式: 1.对象与法::class="{'active':isActive}" 此时当isActive为true时,会拥有active 2.数组语法: ...
- fiddler近期用到的一些新功能
一,AutoResponder导出导入 将AutoResponder中的规则全部选中,右键选择 Export All,可以导出成rule.farx文件 导入时选择Add Rule右边的Import按钮 ...
- mysql trigger 备忘
最近用mysql有这么一个需求 item表:id,item,url,websiteid website表:id,domain item表示从不同网站获取的信息 website表示获得信息的网站,其中的 ...
- 关于Mysql的主从
mysql 主从同步异常原因及恢复: 1,auto.cnf 配置问题 这个问题是在部署主从复制的时候,可能会遇到 [1]报错 Last_IO_Error: Fatal error: The sla ...
- 对TSNU网站的初步分析
这是一个教育网的网站,其中网站的教务子系统,html页面是用表单嵌套来格式化显示样式的,另外还有<div>.<iframe>等等 .在这个上有个form表单,提交的参数有如下几 ...
- javascript window对象常用方法
方法名称 prompt():显示可提示用户输入的对话框 alert():显示带有一个提示信息和 一个确定按钮的警示框 confirm():显示一个 带有提示信息.确定和取消按钮的对话框 open(): ...
- 学习php
一.php是什么? 1.PHP:Hypertext Preprocessor(超文本预处理语言),是一种开源脚本语言. 2.PHP是脚本语言 3.PHP最流行的网站开发语言 4.PHP官网:http: ...