SpringMVC Controller接收前台ajax的GET或POST请求返回各种参数

本文主要是介绍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错误处理

网上分析原因很多,但找了很久都没解决,基本是以下几类:

  1. springmvc添加配置、注解;
  2. pom.xml添加jackson包引用;
  3. Ajax请求时没有设置Content-Type为application/json
  4. 发送的请求内容不要转成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-8</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-8</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.1</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-lgpl</artifactId><version>1.8.1</version></dependency></span>

spring4.x, pom.xml添加如下配置

        <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.5.2</version></dependency><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请求是将数据以什么形式传递到后台,这里我总结了三种形式

  1. POST + JSON字符串形式
  2. POST + JSON对象形式
  3. 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") @ResponseBodypublic 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());}  

其他可以参考的文章:
Spring MVC 学习笔记 json格式的输入和输出
帮我找到解决异常问题的国外论坛贴
SpringMVC+ajax返回JSON串
springMVC框架下JQuery传递并解析Json数据
spring mvc 处理 Ajax

这篇关于SpringMVC Controller接收前台ajax的GET或POST请求返回各种参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1066272

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.