springmvc Controller 接收前端ajax的 get post请求返回各类参数

这几天写新项目遇到这个问题,看这位博主总结得不错,懒得写了,直接转!原文:http://blog.csdn.net/yixiaoping/article/details/45281721javascript

闲话少说,刚开始用SpringMVC, 页面要使用jquery的ajax请求Controller。 但老是失败,主要表现为如下两个异常为:java

异常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverterjquery

异常二:SpringMVC @ResponseBody 415错误处理web

网上分析缘由不少,但找了好久都没解决,基本是如下几类:ajax

springmvc添加配置、注解;
pom.xml添加jackson包引用;
Ajax请求时没有设置Content-Type为application/json
发送的请求内容不要转成JSON对象,直接发送JSON字符串便可
这些其实都没错!!!
如下是我分析的解决步骤方法:spring

(1)springMVC配置文件开启注解json

1
2
(2)添加springMVC须要添加以下配置。 (这个要注意spring版本,3.x和4.x配置不一样)markdown

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
具体能够查看spring-web的jar确认,哪一个存在用哪一个!
spring3.x配置:mvc

复制代码






app

<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

复制代码
spring4.x配置:

复制代码






<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

复制代码
(3)pom.xml添加jackson依赖(这个要注意spring版本,3.x和4.x配置不一样)

若是是spring 3.x,pom.xml添加以下配置

复制代码

org.codehaus.jackson
jackson-core-lgpl
1.8.1

<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-lgpl</artifactId>
        <version>1.8.1</version>
    </dependency></span>

复制代码
spring4.x, pom.xml添加以下配置

复制代码

com.fasterxml.jackson.core
jackson-core
2.5.2

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.2</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 unlock(HttpEntity 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());
}
posted @ 2017-09-23 16:32  hptjzzj 阅读( ...) 评论( ...) 编辑 收藏

相关文章
相关标签/搜索