SpringMVC:整合JQUERY与JSON

SpringMVC:整合JQUERY与JSON
引用别处
博客分类: Spring
jsonjQueryAjaxITeyeWeb
参考资料
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必须注意二点
1 必须包含:jackson的jar包,我使用的是: jackson-all-1.8.1.jar,
可在官网:http://mvnrepository.com/artifact/org.codehaus.jackson中去下载
2 在springmvc.xml配置文件中必配置: <mvc:annotation-driven/>
3 jquery.json-*.*.min.js
实现功能: 从后台获取对象,List,Map在前台显示,前台提交JSON数据格式到后台并且返回
一 工程相关图片
1 工程图片

2 效果图片

二 具体代码
1 springmvc.xml
Xml代码 
<?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:p="http://www.springframework.org/schema/p" 
    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-3.0.xsd 
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd 
        http://www.springframework.org/schema/mvc     
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
    <!--  
        自动搜索@Controller标注的类 
        用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。 
    --> 
    <context:component-scan base-package="com.liuzd.sj.web" />     
    <mvc:annotation-driven/>           
 
    <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> 
    <bean 
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> 
    <!--  
    <bean 
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
        <property name="messageConverters"> 
            <list> 
                <bean 
                    class="org.springframework.http.converter.StringHttpMessageConverter"> 
                    <property name="supportedMediaTypes"> 
                        <list> 
                            <value>text/html;charset=UTF-8</value> 
                        </list> 
                    </property> 
                </bean> 
            </list> 
        </property> 
    </bean> 
    <bean id="mappingJacksonHttpMessageConverter" 
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 
         
    --> 
</beans> 

2 springmvc与jquery整合页面
Html代码 
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script>  
    <title>Spring MVC - jQuery 整合教程</title> 
</head> 
<body> 
<h3>Spring MVC - jQuery 整合教程</h3> 
<h4>AJAX version</h4> 
<p>Demo 1 计算并返回值</p> 
<div style="border: 1px solid #ccc; width: 250px;"> 
    Add Two Numbers: <br/> 
    <input id="inputNumber1" type="text" size="5"> + 
    <input id="inputNumber2" type="text" size="9"> 
    <input type="submit" id="demo1" value="Add" /> <br/> 
    Sum: <br> 
    <span id="sum">(Result will be shown here)</span> 
</div> 
<hr><br> 
<p>Demo 2 获取一个对象</p> 
<div style="border: 1px solid #ccc; width: 250px;"> 
    <select id="userId">       
        <c:forEach var="index" begin="1" end="5" step="1"> 
            <option value="${index}">${index}</option> 
        </c:forEach> 
    </select> 
    <input type="submit" id="demo2" value="Get" /> <br/>     
    <span id="info">(Result will be shown here)</span> 
</div> 
<hr><br> 
<p>Demo 3 返回List集合对象</p> 
<div style="border: 1px solid #ccc; width: 250px;">    
    <input type="submit" id="demo3" value="Get List User" /> <br/>   
    <span id="listInfo">(Result will be shown here)</span> 
</div> 
<hr><br> 
<p>Demo 4 返回Map集合对象</p> 
<div style="border: 1px solid #ccc; width: 250px;">    
    <input type="submit" id="demo4" value="Get Map User" /> <br/>    
    <span id="mapInfo">(Result will be shown here)</span> 
</div> 
<hr><br> 
<a href="${pageContext.request.contextPath}/index.jsp">返回</a> 
<hr><br> 
<script type="text/javascript">  
$(function() { 
     $("#demo1").click(function(){ 
        $.post("${pageContext.request.contextPath}/main/ajax/add.do", 
                    {inputNumber1:  $("#inputNumber1").val(), 
                     inputNumber2:  $("#inputNumber2").val()  
                    }, 
                    function(data){                                                                              
                        $("#sum").replaceWith('<span id="sum">'+ data + '</span>');                             
                    }); 
     }); 
      
      $("#demo2").click(function(){ 
        var userId = $("#userId").val(); 
        $.post("${pageContext.request.contextPath}/main/ajax/getUser/"+userId+".do", 
                    null, 
                    function(data){      
                        var info = "姓名: " + data.name+",年龄: " + data.age + ",地址: " + data.address + ",性别: " + (data.sex == 1 ? "男" : "女")+",密码: " + data.password;                                                                       
                        $("#info").html(info);                              
                    }); 
     }); 
      
      $("#demo3").click(function(){    
        $.post("${pageContext.request.contextPath}/main/ajax/userList.do", 
                    null, 
                    function(data){  
                            /*                           
                            var info = '';   
                            var leng = data.length;                                                  
                            for(var i=0;i<leng;i++){ 
                              info += data[i].id + "," + data[i].name + "," + data[i].sex + "," + data[i].password + "," + data[i].address + "," + data[i].age+"<br>"; 
                            }                                                                            
                            $("#listInfo").html(info);  */ 
                             
                            var info = '';   
                             $.each(data,function(index,entity) {  
                               info += "姓名: " + entity.name+",年龄: " + entity.age + ",地址: " + entity.address + ",性别: " + (entity.sex == 1 ? "男" : "女")+",密码: " + entity.password+"<br>";    
                             }); 
                             $("#listInfo").html(info); 
                               
                                                                        
                    }); 
     });      
      
     $("#demo4").click(function(){     
        $.post("${pageContext.request.contextPath}/main/ajax/userMap.do", 
                    null, 
                    function(map){   
                         var info = '';  
                         $.each(map,function(key,values) {  
                               info += "key="+key+"<br>"; 
                               $(values).each(function(){       
                                   info += "姓名: " + this.name+",年龄: " + this.age + ",地址: " + this.address + ",性别: " + (this.sex == 1 ? "男" : "女")+",密码: " + this.password+"<br>"; 
                                });     
                                  
                         }); 
                         $("#mapInfo").html(info);                  
                    }); 
     });      
      
      
      
}); 
</script> 
</body> 
</html> 

3 springmvc与jquery整合后台代码
Java代码 
package com.liuzd.sj.web; 
 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import com.liuzd.sj.entity.User; 
 
@Controller 
@RequestMapping("/main/ajax") 
public class AjaxController { 
 
    /**
     * 根据映射跳转到指定的页面
     */ 
    @RequestMapping(value = "/add", method = RequestMethod.GET) 
    public String getAjaxAddPage() { 
        // 解析 /WEB-INF/jsp/ajax-add-page.jsp 
        return "ajax-add-page"; 
    } 
 
    /**  
     * 提交表单并进行运算.
     */ 
    @RequestMapping(value = "/add", method = RequestMethod.POST) 
    public @ResponseBody Integer add( 
            @RequestParam(value = "inputNumber1", required = true)Integer inputNumber1, 
            @RequestParam(value = "inputNumber2", required = true)Integer inputNumber2) { 
        // 实现运算 
        Integer sum = inputNumber1 + inputNumber2; 
        System.out.println("sum: " + sum); 
        // @ResponseBody 会自动的将返回值转换成JSON格式 
        // 但是你必须添加jackson的jar包!!! 
        return sum; 
    }    
 
    @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.POST) 
    public @ResponseBody User getUser(@PathVariable("userId")String  userId) { 
        System.out.println("根据ID获取用户对象: " + userId);         
        Map<String,User> users = new HashMap<String,User>(); 
        users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23)); 
        users.put("2", new User("565676", "张三", "123", "北京市", "2", 53)); 
        users.put("3", new User("325566", "李四", "123", "河南省", "2", 93)); 
        users.put("4", new User("989654", "刘邦", "123", "蒙古包", "1", 13)); 
        users.put("5", new User("234444", "王熙凤", "123", "成都市", "1", 43));        
        return users.get(userId); 
    } 
 
    @RequestMapping(value = "/userList", method = RequestMethod.POST) 
    public @ResponseBody 
    List<User> getUsers() {        
        List<User> users = new ArrayList<User>(); 
        users.add(new User("123456", "李逵", "123", "成都市", "1", 23)); 
        users.add(new User("123457", "李四", "124", "北京市", "2", 53)); 
        users.add(new User("123458", "李三", "125", "河南市", "0", 73)); 
        users.add(new User("123459", "李五", "126", "大路市", "3", 93)); 
        return users; 
    } 
     
    @RequestMapping(value = "/userMap", method = RequestMethod.POST) 
    public @ResponseBody Map<String,User> getUserMap() {       
        Map<String,User> users = new HashMap<String,User>(); 
        users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23)); 
        users.put("2",new User("123457", "李四", "124", "北京市", "2", 53)); 
        users.put("3",new User("123458", "李三", "125", "河南市", "0", 73)); 
        users.put("4",new User("123459", "李五", "126", "大路市", "3", 93)); 
        return users; 
    } 


4 sprinmcv与jquery,json整合页面
Html代码 
<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
    <title>Spring MVC</title>    
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script> 
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery.json-2.2.min.js"></script>    
    <script type="text/javascript">        
            
        $(document).ready(function(){    
         
              jQuery.ajax( {    
                type : 'GET',    
                contentType : 'application/json',    
                url : '${pageContext.request.contextPath}/user/list.do',    
                dataType : 'json',    
                success : function(data) {    
                  if (data && data.success == "true") {    
                    $('#info').html("共" + data.total + "条数据。<br/>");    
                    $.each(data.data, function(i, item) {    
                      $('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"<br>");    
                    });    
                  }    
                },    
                error : function() {    
                  alert("error")    
                }    
              });   
                
              $("#submit").click(function() {    
                var jsonuserinfo = $.toJSON($('#form').serializeObject());    
                alert(jsonuserinfo);    
                jQuery.ajax( {    
                  type : 'POST',    
                  contentType : 'application/json',    
                  url : '${pageContext.request.contextPath}/user/add.do',    
                  data : jsonuserinfo,    
                  dataType : 'json',    
                  success : function(data) {    
                     if (data && data.success == "true") {    
                        $('#info').html("共" + data.total + "条数据。<br/>");    
                        $.each(data.data, function(i, item) {    
                          $('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"<br>");    
                        }); 
                         alert("新增成功!");       
                      }                     
                  },    
                  error : function(data) {    
                    alert("error")    
                  }    
                });    
              });    
            });   
             
            //将一个表单的数据返回成JSON对象    
            $.fn.serializeObject = function() {    
              var o = {};    
              var a = this.serializeArray();    
              $.each(a, function() {    
                if (o[this.name]) {    
                  if (!o[this.name].push) {    
                    o[this.name] = [ o[this.name] ];    
                  }    
                  o[this.name].push(this.value || '');    
                } else {    
                  o[this.name] = this.value || '';    
                }    
              });    
              return o;    
            };    
    </script> 
</head>    
<body>    
<div id="info"></div>    
<form action="add" method="post" id="form">    
编号:<input type="text" name="id"/>    
姓名:<input type="text" name="name"/>    
年龄:<input type="text" name="age"/>  
性别: <select name="sex"> 
            <option value="1">男</option> 
            <option value="2">女</option> 
     </select> 
密码: <input name="password">       
地址:<input name="address"/> 
           
<input type="button" value="提交" id="submit"/>    
</form>    
</body>    
</html>   

5 sprinmcv与jquery,json后台代码
Java代码 
package com.liuzd.sj.web; 
 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.http.HttpEntity; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.ModelAttribute; 
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.bind.annotation.SessionAttributes; 
 
import com.liuzd.sj.entity.User; 
 
@Controller 
@RequestMapping("/user") 
@SessionAttributes("users") 
public class DemoController { 
 
    @RequestMapping(value = "/list", method = RequestMethod.GET) 
    @ModelAttribute("users") 
    @ResponseBody 
    public Map<String, Object> getUserMaps() { 
 
        List<User> list = new ArrayList<User>(); 
        User um = new User(); 
        um.setId("1"); 
        um.setName("sss"); 
        um.setAge(66); 
        list.add(um); 
         
        um = new User(); 
        um.setId("2"); 
        um.setName("aaa"); 
        um.setAge(44); 
        list.add(um); 
         
        Map<String, Object> modelMap = new HashMap<String, Object>(); 
        modelMap.put("total", list.size()); 
        modelMap.put("data", list); 
        modelMap.put("success", "true"); 
        return modelMap; 
    } 
 
      @RequestMapping(value = "/add", method = RequestMethod.POST)    
      @ResponseBody    
      //二种方式: A HttpEntity<User>  B使用注解 @ResponseBody 
      public Map<String, Object> addUser(HttpEntity<User> model,javax.servlet.http.HttpServletRequest request) {    
        System.out.println("user: " + model.getBody()); 
     
        Map<String, Object> map = (Map)request.getSession().getAttribute("users"); 
        if(null == map){ 
            map = getUserMaps(); 
        } 
        List<User> list = (List<User>)map.get("data"); 
        list.add(model.getBody()); 
        map.put("total", list.size()); 
        map.put("data", list); 
        request.getSession().setAttribute("users",map); 
        return map; 
    } 
 
 
    @RequestMapping("/ajaxPage") 
    public String ajaxAddPage() { 
        return "ajax-add-page2"; 
    } 


6 web.xml
Xml代码 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">     
     
    <context-param> 
       <param-name>log4jConfigLocation</param-name> 
       <param-value>/WEB-INF/classes/log4j.properties</param-value> 
    </context-param>  
     
     <context-param> 
      <param-name>log4jRefreshInterval</param-name> 
      <param-value>60000</param-value> 
     </context-param>  
     <context-param> 
        <param-name>log4jExposeWebAppRoot</param-name> 
        <param-value>false</param-value> 
    </context-param>   
     
    <listener> 
       <listener-class> 
            org.springframework.web.util.Log4jConfigListener 
       </listener-class> 
    </listener>  
 
    <filter> 
        <filter-name>encodingFilter</filter-name> 
        <filter-class> 
            org.springframework.web.filter.CharacterEncodingFilter 
        </filter-class> 
        <init-param> 
            <param-name>encoding</param-name> 
            <param-value>UTF-8</param-value> 
        </init-param> 
        <init-param>    
            <param-name>forceEncoding</param-name>    
            <param-value>false</param-value>    
        </init-param>   
    </filter> 
 
    <filter-mapping> 
        <filter-name>encodingFilter</filter-name> 
        <url-pattern>*.do</url-pattern> 
    </filter-mapping> 
     
    <filter-mapping> 
        <filter-name>encodingFilter</filter-name> 
        <url-pattern>*.jsp</url-pattern> 
    </filter-mapping> 
 
    <servlet> 
        <servlet-name>springmvc</servlet-name> 
        <servlet-class> 
            org.springframework.web.servlet.DispatcherServlet 
        </servlet-class>       
        <init-param> 
            <param-name>contextConfigLocation</param-name>                            
             <param-value>classpath:springmvc.xml</param-value> 
        </init-param>  
        <load-on-startup>1</load-on-startup> 
    </servlet> 
 
    <servlet-mapping> 
        <servlet-name>springmvc</servlet-name> 
        <url-pattern>*.do</url-pattern> 
    </servlet-mapping> 
     
      
    <welcome-file-list> 
        <welcome-file>index.jsp</welcome-file> 
    </welcome-file-list> 
 
</web-app> 

猜你喜欢

转载自skywhsq1987.iteye.com/blog/1602037