SpringMVC环境下实现的Ajax异步请求(JSON格式数据)

简介:

一 环境搭建

首先是常规的spring mvc环境搭建,不用多说,需要注意的是,这里需要引入jackson相关jar包,然后在spring配置文件“springmvc-servlet.xml”中添加json解析相关配置,我这里的完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans  xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns:context = "http://www.springframework.org/schema/context"
     xmlns:mvc = "http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
     
     <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
     < bean  id = "mappingJacksonHttpMessageConverter"
         class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
         < property  name = "supportedMediaTypes" >
             < list >
                 < value >text/html;charset=UTF-8</ value >
                 < value >application/json;charset=UTF-8</ value >
             </ list >
         </ property >
         < property  name = "objectMapper" >
             < bean  class = "org.codehaus.jackson.map.ObjectMapper" >
                 < property  name = "dateFormat" >
                     < bean  class = "java.text.SimpleDateFormat" >
                         < constructor-arg  type = "java.lang.String"  value = "yyyy-MM-dd HH:mm:ss" ></ constructor-arg >
                     </ bean >
                 </ property >
             </ bean >
         </ property >
     </ bean >
     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
     < bean
         class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
         < property  name = "messageConverters" >
             < list >
                 < ref  bean = "mappingJacksonHttpMessageConverter"  /> <!-- json转换器 -->
             </ list >
         </ property >
     </ bean >
     < mvc:annotation-driven
         content-negotiation-manager = "contentNegotiationManager"  />
     < bean  id = "contentNegotiationManager"
         class = "org.springframework.web.accept.ContentNegotiationManagerFactoryBean" >
         <!-- true,开启扩展名支持,false关闭支持 -->
         < property  name = "favorPathExtension"  value = "false"  />
         <!-- 用于开启 /userinfo/123?format=json的支持 -->
         < property  name = "favorParameter"  value = "true"  />
         <!-- 设置为true以忽略对Accept Header的支持 -->
         < property  name = "ignoreAcceptHeader"  value = "false"  />
         < property  name = "mediaTypes" >
             < value >
                 atom=application/atom+xml
                 html=text/html
                 json=application/json
                 xml=application/xml
                 *=*/*
             </ value >
         </ property >
     </ bean >
     < context:annotation-config  />
     <!-- 启动自动扫描该包下所有的Bean(例如@Controller) -->
     < context:component-scan  base-package = "cn.zifangsky.controller"  />
 
     < mvc:default-servlet-handler  />
     <!-- 定义视图解析器 -->
     < bean  id = "jspViewResolver"
         class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
         < property  name = "requestContextAttribute"  value = "rc"  />
         < property  name = "viewClass"
             value = "org.springframework.web.servlet.view.JstlView"  />
         < property  name = "prefix"  value = "/WEB-INF/jsp/"  />
         < property  name = "suffix"  value = ".jsp"  />
         < property  name = "order"  value = "1" ></ property >
     </ bean >
 
</ beans >

项目结构:

wKioL1ceL1_RzTmBAAA1S10S6x0204.png


注:我这里测试使用的完整jar包:http://pan.baidu.com/s/1dEUwdmL

仅供参考


二 测试实例

(1)在WEB-INF/jsp目录下新建了一个index.jsp文件,包含了简单的jQuery的ajax请求,请求数据的格式是JSON,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<%
     String path = request.getContextPath();
     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
             + path + "/";
%>
 
< html >
< head >
< meta  http-equiv = "Content-Type"  content = "text/html; charset=UTF-8" >
< base  href="<%=basePath%>">
< script  type = "text/javascript"  src = "scripts/jquery/jquery-1.6.2.min.js" ></ script >
< script  type = "text/javascript"  src = "scripts/jquery/jquery.i18n.properties-min-1.0.9.js" ></ script >
< script  type = "text/javascript"  src = "scripts/jquery/jquery.autocomplete.js" ></ script >
< script   type = "text/javascript"  src = "scripts/jquery/jquery.loadmask.js" ></ script >
< script  type = "text/javascript"  src = "scripts/jquery/jquery.form.js" ></ script >
< script  type = "text/javascript"  src = "scripts/jquery/jquery.timers.js" ></ script >
< title >jQuery i18n</ title >
< script  type = "text/javascript" >
     $().ready(
             function() {
                 $("#sub").click(
                         function() {
                             var name = $("#username").val();
                             var age = 18;
                             var user = {"username":name,"age":age};
                             $.ajax({
                                         url : 'hello.json',
                                         type : 'POST',
                                         data : JSON.stringify(user), // Request body 
                                         contentType : 'application/json; charset=utf-8',
                                         dataType : 'json',
                                         success : function(response) {
                                             //请求成功
                                             alert("你好" + response.username + "[" + response.age + "],当前时间是:" + response.time + ",欢迎访问:http://www.zifangsky.cn");
                                             
                                         },
                                         error : function(msg) {
                                             alert(msg);
                                         }
                                     });
                         });
             });
</ script >
</ head >
< body >
     < input  type = "text"  id = "username"
         style = "width: 100px; height: 30px; font-size: 20px; font-weight: bold;" >
     < input  type = "button"  id = "sub"  value = "Go"
         style = "height: 40px; height: 30px;" >
     < br >
</ body >
</ html >

(2)一个简单的model类User,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package  cn.zifangsky.controller;
 
public  class  User {
     private  String username;
     private  int  age;
     public  String getUsername() {
         return  username;
     }
     public  void  setUsername(String username) {
         this .username = username;
     }
     public  int  getAge() {
         return  age;
     }
     public  void  setAge( int  age) {
         this .age = age;
     }
     
}

(3)controller类TestController.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package  cn.zifangsky.controller;
 
import  java.text.Format;
import  java.text.SimpleDateFormat;
import  java.util.Date;
import  java.util.HashMap;
import  java.util.Map;
 
import  org.springframework.context.annotation.Scope;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestBody;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
import  org.springframework.web.bind.annotation.ResponseBody;
import  org.springframework.web.servlet.ModelAndView;
 
@Controller
@Scope ( "prototype" )
public  class  TestController {
 
     /**
      * 转到页面
      */
     @RequestMapping (value =  "/hello.html" )
     public  ModelAndView list() {
         ModelAndView view =  new  ModelAndView( "index" );
         return  view;
     }
 
     /**
      * ajax异步请求, 请求格式是json
      */
     @RequestMapping (value =  "/hello.json" , method = { RequestMethod.POST })
     @ResponseBody
     public  Map<String, String> hello( @RequestBody  User user) {
         // 返回数据的Map集合
         Map<String, String> result =  new  HashMap<String, String>();
 
         Format format =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
 
         // 返回请求的username
         result.put( "username" , user.getUsername());
         // 返回年龄
         result.put( "age" , String.valueOf(user.getAge()));
         // 返回当前时间
         result.put( "time" , format.format( new  Date()));
 
         return  result;
     }
}

关于具体的执行步骤我简单说一下:


i)项目启动后,在浏览器中访问:http://localhost:8089/SpringDemo/hello.html,然后会转到执行controller中的list方法,接着会转到/WEB-INF/jsp/index.jsp(PS:在controller中返回的是逻辑视图,跟在springmvc-servlet.xml文件中定义的路径前缀和后缀进行拼接后合成文件的真正路径)


ii)在index.jsp页面输入文字然后点击按钮,将会触发ajax请求,这个请求会获取输入框中的数据和默认的“age”参数拼接成json格式字符串最后提交到“hello.json”这个请求,也就是执行controller中的hello方法


iii)hello方法执行完毕后会返回一系列数据最后在页面中显示出来




(4)效果如下:

wKiom1ceLxKTLKMqAABmEB8LihM051.png



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1767692,如需转载请自行联系原作者


相关文章
|
23天前
|
JSON 前端开发 Java
Json格式数据解析
Json格式数据解析
|
2月前
|
缓存 前端开发 Java
Spring MVC 面试题及答案整理,最新面试题
Spring MVC 面试题及答案整理,最新面试题
97 0
|
2月前
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
11 0
|
2月前
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
9 0
|
2月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
26 0
|
2月前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
45 1
|
2天前
|
存储 JSON DataWorks
DataWorks产品使用合集之DataWorks将 MongoDB 中的数组类型写入到 DataWorks 的单个字段时,表示为字符串格式而非 JSON 格式如何解决
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
9 3
|
14天前
|
前端开发 JavaScript
ajax框架格式,每个属性的作用
ajax框架格式,每个属性的作用
16 7
|
17天前
|
存储 JSON NoSQL
MongoDB的文档存储格式BSON和JSON的区别
MongoDB的文档存储格式BSON和JSON的区别
|
19天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
23 3