springMVC 与 jquery 整合

引用:http://liuzidong.iteye.com/blog/1069343

http://www.cnblogs.com/zhangliang0115/category/359684.html

参考资料 
1 Spring3 MVC 笔记(二) —json+rest优化 
http://7454103.iteye.com/?show_full=true 
2 jquery 遍历对象、数组、集合 
http://blog.sina.com.cn/s/blog_5db0dfe40100hay7.html 
3 jquery 遍历 map(callback) 
http://kaxu.iteye.com/blog/308367 
4  Jquery的map遍历 
http://blog.csdn.net/niu870781892/archive/2010/04/13/5479850.aspx 
5 Spring mvc3的ajax 
http://xace.iteye.com/blog/731263 
6 Spring MVC 学习笔记 九 json格式的输入和输出 
http://starscream.iteye.com/blog/1067606 

在SpringMVC中使用JSON必须注意二点 
必须包含:jackson的jar包,我使用的是: jackson-all-1.8.1.jar, 
可在官网:http://mvnrepository.com/artifact/org.codehaus.jackson中去下载 
在springmvc.xml配置文件中必配置: <mvc:annotation-driven/> 
3 jquery.json-*.*.min.js 
实现功能: 从后台获取对象,List,Map在前台显示,前台提交JSON数据格式到后台并且返回 
一 工程相关图片 
1 工程图片 
 
2 效果图片 
 
二 具体代码 
1 springmvc.xml 
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  10.         http://www.springframework.org/schema/context   
  11.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  12.         http://www.springframework.org/schema/mvc      
  13.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  14.     <!--   
  15.         自动搜索@Controller标注的类  
  16.         用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。  
  17.     -->  
  18.     <context:component-scan base-package="com.liuzd.sj.web" />      
  19.     <mvc:annotation-driven/>            
  20.   
  21.     <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->  
  22.     <bean  
  23.         class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  24.         p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />  
  25.     <!--   
  26.     <bean  
  27.         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  28.         <property name="messageConverters">  
  29.             <list>  
  30.                 <bean  
  31.                     class="org.springframework.http.converter.StringHttpMessageConverter">  
  32.                     <property name="supportedMediaTypes">  
  33.                         <list>  
  34.                             <value>text/html;charset=UTF-8</value>  
  35.                         </list>  
  36.                     </property>  
  37.                 </bean>  
  38.             </list>  
  39.         </property>  
  40.     </bean>  
  41.     <bean id="mappingJacksonHttpMessageConverter"  
  42.         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  
  43.           
  44.     -->  
  45. </beans>  

2 springmvc与jquery整合页面 
Html代码  收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>  
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7.     <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script>   
  8.     <title>Spring MVC - jQuery 整合教程</title>  
  9. </head>  
  10. <body>  
  11. <h3>Spring MVC - jQuery 整合教程</h3>  
  12. <h4>AJAX version</h4>  
  13. <p>Demo 1 计算并返回值</p>  
  14. <div style="border: 1px solid #ccc; width: 250px;">  
  15.     Add Two Numbers: <br/>  
  16.     <input id="inputNumber1" type="text" size="5"> +  
  17.     <input id="inputNumber2" type="text" size="9">  
  18.     <input type="submit" id="demo1" value="Add" /> <br/>  
  19.     Sum: <br>  
  20.     <span id="sum">(Result will be shown here)</span>  
  21. </div>  
  22. <hr><br>  
  23. <p>Demo 2 获取一个对象</p>  
  24. <div style="border: 1px solid #ccc; width: 250px;">  
  25.     <select id="userId">        
  26.         <c:forEach var="index" begin="1" end="5" step="1">  
  27.             <option value="${index}">${index}</option>  
  28.         </c:forEach>  
  29.     </select>  
  30.     <input type="submit" id="demo2" value="Get" /> <br/>      
  31.     <span id="info">(Result will be shown here)</span>  
  32. </div>  
  33. <hr><br>  
  34. <p>Demo 3 返回List集合对象</p>  
  35. <div style="border: 1px solid #ccc; width: 250px;">     
  36.     <input type="submit" id="demo3" value="Get List User" /> <br/>    
  37.     <span id="listInfo">(Result will be shown here)</span>  
  38. </div>  
  39. <hr><br>  
  40. <p>Demo 4 返回Map集合对象</p>  
  41. <div style="border: 1px solid #ccc; width: 250px;">     
  42.     <input type="submit" id="demo4" value="Get Map User" /> <br/>     
  43.     <span id="mapInfo">(Result will be shown here)</span>  
  44. </div>  
  45. <hr><br>  
  46. <a href="${pageContext.request.contextPath}/index.jsp">返回</a>  
  47. <hr><br>  
  48. <script type="text/javascript">   
  49. $(function() {  
  50.      $("#demo1").click(function(){  
  51.         $.post("${pageContext.request.contextPath}/main/ajax/add.do",  
  52.                     {inputNumber1:  $("#inputNumber1").val(),  
  53.                      inputNumber2:  $("#inputNumber2").val()   
  54.                     },  
  55.                     function(data){                                                                               
  56.                         $("#sum").replaceWith('<span id="sum">'+ data + '</span>');                              
  57.                     });  
  58.      });  
  59.        
  60.       $("#demo2").click(function(){  
  61.         var userId = $("#userId").val();  
  62.         $.post("${pageContext.request.contextPath}/main/ajax/getUser/"+userId+".do",  
  63.                     null,  
  64.                     function(data){       
  65.                         var info = "姓名: " + data.name+",年龄: " + data.age + ",地址: " + data.address + ",性别: " + (data.sex == 1 ? "男" : "女")+",密码: " + data.password;                                                                        
  66.                         $("#info").html(info);                               
  67.                     });  
  68.      });  
  69.        
  70.       $("#demo3").click(function(){     
  71.         $.post("${pageContext.request.contextPath}/main/ajax/userList.do",  
  72.                     null,  
  73.                     function(data){   
  74.                             /*                            
  75.                             var info = '';    
  76.                             var leng = data.length;                                                   
  77.                             for(var i=0;i<leng;i++){  
  78.                               info += data[i].id + "," + data[i].name + "," + data[i].sex + "," + data[i].password + "," + data[i].address + "," + data[i].age+"<br>";  
  79.                             }                                                                             
  80.                             $("#listInfo").html(info);  */  
  81.                               
  82.                             var info = '';    
  83.                              $.each(data,function(index,entity) {   
  84.                                info += "姓名: " + entity.name+",年龄: " + entity.age + ",地址: " + entity.address + ",性别: " + (entity.sex == 1 ? "男" : "女")+",密码: " + entity.password+"<br>";     
  85.                              });  
  86.                              $("#listInfo").html(info);  
  87.                                 
  88.                                                                          
  89.                     });  
  90.      });       
  91.        
  92.      $("#demo4").click(function(){      
  93.         $.post("${pageContext.request.contextPath}/main/ajax/userMap.do",  
  94.                     null,  
  95.                     function(map){    
  96.                          var info = '';   
  97.                          $.each(map,function(key,values) {   
  98.                                info += "key="+key+"<br>";  
  99.                                $(values).each(function(){        
  100.                                    info += "姓名: " + this.name+",年龄: " + this.age + ",地址: " + this.address + ",性别: " + (this.sex == 1 ? "男" : "女")+",密码: " + this.password+"<br>";  
  101.                                 });      
  102.                                    
  103.                          });  
  104.                          $("#mapInfo").html(info);                   
  105.                     });  
  106.      });       
  107.        
  108.        
  109.        
  110. });  
  111. </script>  
  112. </body>  
  113. </html>  

3 springmvc与jquery整合后台代码 
Java代码  收藏代码
  1. package com.liuzd.sj.web;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import org.springframework.web.bind.annotation.RequestParam;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14.   
  15. import com.liuzd.sj.entity.User;  
  16.   
  17. @Controller  
  18. @RequestMapping("/main/ajax")  
  19. public class AjaxController {  
  20.   
  21.     /** 
  22.      * 根据映射跳转到指定的页面 
  23.      */  
  24.     @RequestMapping(value = "/add", method = RequestMethod.GET)  
  25.     public String getAjaxAddPage() {  
  26.         // 解析 /WEB-INF/jsp/ajax-add-page.jsp  
  27.         return "ajax-add-page";  
  28.     }  
  29.   
  30.     /**   
  31.      * 提交表单并进行运算. 
  32.      */  
  33.     @RequestMapping(value = "/add", method = RequestMethod.POST)  
  34.     public @ResponseBody Integer add(  
  35.             @RequestParam(value = "inputNumber1", required = true)Integer inputNumber1,  
  36.             @RequestParam(value = "inputNumber2", required = true)Integer inputNumber2) {  
  37.         // 实现运算  
  38.         Integer sum = inputNumber1 + inputNumber2;  
  39.         System.out.println("sum: " + sum);  
  40.         // @ResponseBody 会自动的将返回值转换成JSON格式  
  41.         // 但是你必须添加jackson的jar包!!!  
  42.         return sum;  
  43.     }     
  44.   
  45.     @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.POST)  
  46.     public @ResponseBody User getUser(@PathVariable("userId")String  userId) {  
  47.         System.out.println("根据ID获取用户对象: " + userId);          
  48.         Map<String,User> users = new HashMap<String,User>();  
  49.         users.put("1"new User("123456""李逵""123""成都市""1"23));  
  50.         users.put("2"new User("565676""张三""123""北京市""2"53));  
  51.         users.put("3"new User("325566""李四""123""河南省""2"93));  
  52.         users.put("4"new User("989654""刘邦""123""蒙古包""1"13));  
  53.         users.put("5"new User("234444""王熙凤""123""成都市""1"43));         
  54.         return users.get(userId);  
  55.     }  
  56.   
  57.     @RequestMapping(value = "/userList", method = RequestMethod.POST)  
  58.     public @ResponseBody  
  59.     List<User> getUsers() {         
  60.         List<User> users = new ArrayList<User>();  
  61.         users.add(new User("123456""李逵""123""成都市""1"23));  
  62.         users.add(new User("123457""李四""124""北京市""2"53));  
  63.         users.add(new User("123458""李三""125""河南市""0"73));  
  64.         users.add(new User("123459""李五""126""大路市""3"93));  
  65.         return users;  
  66.     }  
  67.       
  68.     @RequestMapping(value = "/userMap", method = RequestMethod.POST)  
  69.     public @ResponseBody Map<String,User> getUserMap() {        
  70.         Map<String,User> users = new HashMap<String,User>();  
  71.         users.put("1"new User("123456""李逵""123""成都市""1"23));  
  72.         users.put("2",new User("123457""李四""124""北京市""2"53));  
  73.         users.put("3",new User("123458""李三""125""河南市""0"73));  
  74.         users.put("4",new User("123459""李五""126""大路市""3"93));  
  75.         return users;  
  76.     }  
  77. }  

4 sprinmcv与jquery,json整合页面 
Html代码  收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>  
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">     
  7.     <title>Spring MVC</title>     
  8.     <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script>  
  9.     <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery.json-2.2.min.js"></script>     
  10.     <script type="text/javascript">         
  11.              
  12.         $(document).ready(function(){     
  13.           
  14.               jQuery.ajax( {     
  15.                 type : 'GET',     
  16.                 contentType : 'application/json',     
  17.                 url : '${pageContext.request.contextPath}/user/list.do',     
  18.                 dataType : 'json',     
  19.                 success : function(data) {     
  20.                   if (data && data.success == "true") {     
  21.                     $('#info').html("共" + data.total + "条数据。<br/>");     
  22.                     $.each(data.data, function(i, item) {     
  23.                       $('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"<br>");     
  24.                     });     
  25.                   }     
  26.                 },     
  27.                 error : function() {     
  28.                   alert("error")     
  29.                 }     
  30.               });    
  31.                  
  32.               $("#submit").click(function() {     
  33.                 var jsonuserinfo = $.toJSON($('#form').serializeObject());     
  34.                 alert(jsonuserinfo);     
  35.                 jQuery.ajax( {     
  36.                   type : 'POST',     
  37.                   contentType : 'application/json',     
  38.                   url : '${pageContext.request.contextPath}/user/add.do',     
  39.                   data : jsonuserinfo,     
  40.                   dataType : 'json',     
  41.                   success : function(data) {     
  42.                      if (data && data.success == "true") {     
  43.                         $('#info').html("共" + data.total + "条数据。<br/>");     
  44.                         $.each(data.data, function(i, item) {     
  45.                           $('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"<br>");     
  46.                         });  
  47.                          alert("新增成功!");        
  48.                       }                      
  49.                   },     
  50.                   error : function(data) {     
  51.                     alert("error")     
  52.                   }     
  53.                 });     
  54.               });     
  55.             });    
  56.               
  57.             //将一个表单的数据返回成JSON对象     
  58.             $.fn.serializeObject = function() {     
  59.               var o = {};     
  60.               var a = this.serializeArray();     
  61.               $.each(a, function() {     
  62.                 if (o[this.name]) {     
  63.                   if (!o[this.name].push) {     
  64.                     o[this.name] = [ o[this.name] ];     
  65.                   }     
  66.                   o[this.name].push(this.value || '');     
  67.                 } else {     
  68.                   o[this.name] = this.value || '';     
  69.                 }     
  70.               });     
  71.               return o;     
  72.             };     
  73.     </script>  
  74. </head>     
  75. <body>     
  76. <div id="info"></div>     
  77. <form action="add" method="post" id="form">     
  78. 编号:<input type="text" name="id"/>     
  79. 姓名:<input type="text" name="name"/>     
  80. 年龄:<input type="text" name="age"/>   
  81. 性别: <select name="sex">  
  82.             <option value="1"></option>  
  83.             <option value="2"></option>  
  84.      </select>  
  85.  密码: <input name="password">        
  86.  地址:<input name="address"/>  
  87.             
  88. <input type="button" value="提交" id="submit"/>     
  89. </form>     
  90. </body>     
  91. </html>    

5 sprinmcv与jquery,json后台代码 
Java代码  收藏代码
  1. package com.liuzd.sj.web;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.springframework.http.HttpEntity;  
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.web.bind.annotation.ModelAttribute;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.bind.annotation.SessionAttributes;  
  15.   
  16. import com.liuzd.sj.entity.User;  
  17.   
  18. @Controller  
  19. @RequestMapping("/user")  
  20. @SessionAttributes("users")  
  21. public class DemoController {  
  22.   
  23.     @RequestMapping(value = "/list", method = RequestMethod.GET)  
  24.     @ModelAttribute("users")  
  25.     @ResponseBody  
  26.     public Map<String, Object> getUserMaps() {  
  27.   
  28.         List<User> list = new ArrayList<User>();  
  29.         User um = new User();  
  30.         um.setId("1");  
  31.         um.setName("sss");  
  32.         um.setAge(66);  
  33.         list.add(um);  
  34.           
  35.         um = new User();  
  36.         um.setId("2");  
  37.         um.setName("aaa");  
  38.         um.setAge(44);  
  39.         list.add(um);  
  40.           
  41.         Map<String, Object> modelMap = new HashMap<String, Object>();  
  42.         modelMap.put("total", list.size());  
  43.         modelMap.put("data", list);  
  44.         modelMap.put("success""true");  
  45.         return modelMap;  
  46.     }  
  47.   
  48.       @RequestMapping(value = "/add", method = RequestMethod.POST)     
  49.       @ResponseBody     
  50.       //二种方式: A HttpEntity<User>  B使用注解 @ResponseBody  
  51.       public Map<String, Object> addUser(HttpEntity<User> model,javax.servlet.http.HttpServletRequest request) {     
  52.         System.out.println("user: " + model.getBody());  
  53.       
  54.         Map<String, Object> map = (Map)request.getSession().getAttribute("users");  
  55.         if(null == map){  
  56.             map = getUserMaps();  
  57.         }  
  58.         List<User> list = (List<User>)map.get("data");  
  59.         list.add(model.getBody());  
  60.         map.put("total", list.size());  
  61.         map.put("data", list);  
  62.         request.getSession().setAttribute("users",map);  
  63.         return map;  
  64.     }  
  65.   
  66.   
  67.     @RequestMapping("/ajaxPage")  
  68.     public String ajaxAddPage() {  
  69.         return "ajax-add-page2";  
  70.     }  
  71. }  

6 web.xml 
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  5.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">      
  6.       
  7.     <context-param>  
  8.        <param-name>log4jConfigLocation</param-name>  
  9.        <param-value>/WEB-INF/classes/log4j.properties</param-value>  
  10.     </context-param>   
  11.       
  12.      <context-param>  
  13.       <param-name>log4jRefreshInterval</param-name>  
  14.       <param-value>60000</param-value>  
  15.      </context-param>   
  16.      <context-param>  
  17.         <param-name>log4jExposeWebAppRoot</param-name>  
  18.         <param-value>false</param-value>  
  19.     </context-param>    
  20.       
  21.     <listener>  
  22.        <listener-class>  
  23.             org.springframework.web.util.Log4jConfigListener  
  24.        </listener-class>  
  25.     </listener>   
  26.   
  27.     <filter>  
  28.         <filter-name>encodingFilter</filter-name>  
  29.         <filter-class>  
  30.             org.springframework.web.filter.CharacterEncodingFilter  
  31.         </filter-class>  
  32.         <init-param>  
  33.             <param-name>encoding</param-name>  
  34.             <param-value>UTF-8</param-value>  
  35.         </init-param>  
  36.         <init-param>     
  37.             <param-name>forceEncoding</param-name>     
  38.             <param-value>false</param-value>     
  39.         </init-param>    
  40.     </filter>  
  41.   
  42.     <filter-mapping>  
  43.         <filter-name>encodingFilter</filter-name>  
  44.         <url-pattern>*.do</url-pattern>  
  45.     </filter-mapping>  
  46.       
  47.     <filter-mapping>  
  48.         <filter-name>encodingFilter</filter-name>  
  49.         <url-pattern>*.jsp</url-pattern>  
  50.     </filter-mapping>  
  51.   
  52.     <servlet>  
  53.         <servlet-name>springmvc</servlet-name>  
  54.         <servlet-class>  
  55.             org.springframework.web.servlet.DispatcherServlet  
  56.         </servlet-class>        
  57.         <init-param>  
  58.             <param-name>contextConfigLocation</param-name>                             
  59.              <param-value>classpath:springmvc.xml</param-value>  
  60.         </init-param>   
  61.         <load-on-startup>1</load-on-startup>  
  62.     </servlet>  
  63.   
  64.     <servlet-mapping>  
  65.         <servlet-name>springmvc</servlet-name>  
  66.         <url-pattern>*.do</url-pattern>  
  67.     </servlet-mapping>  
  68.       
  69.        
  70.     <welcome-file-list>  
  71.         <welcome-file>index.jsp</welcome-file>  
  72.     </welcome-file-list>  
  73.   
  74. </web-app>  

7 附件为工程原件,只包含jackson-all-1.8.1.jar,其它jar可在相关页面下载
  • 大小: 53.7 KB
  • 大小: 40.4 KB
posted @ 2012-09-19 11:36  镇水古月  阅读(613)  评论(0编辑  收藏  举报