springmvc使用json自動轉換
阿新 • • 發佈:2019-02-15
applicationContext.xml
<!-- 掃描service、dao元件 --> <context:component-scan base-package="com.paincupid.springmvc.*.service,com.paincupid.springmvc.*.persistence" /> <!-- 使用jackson 支援json Java中直接返回類,而不用再使用Json轉換 2015.12.27 --> <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>
java類檔案
程式碼:
package com.paincupid.springmvc.json.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; 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.paincupid.springmvc.log.OpLogger; import com.paincupid.springmvc.log.OpLogger.OpType; import com.paincupid.springmvc.test.domain.Person; import com.paincupid.springmvc.util.BaseJsonRst; import com.paincupid.springmvc.util.CreatMockData; @Controller @RequestMapping("/jqueryFormPluginSimple") public class JqueryFormPluginSimpleController { private static final Logger log = LoggerFactory.getLogger(JqueryFormPluginSimpleController.class); /** * 在前臺的訪問路徑為: http://localhost:8080/springmvc/jqueryFormPluginSimple/list * @param person * @param model * @return */ @RequestMapping("/list") @OpLogger(id = "18611112222", type=OpType.SEARCH) public String listPerson() { return "json/jqueryFormPluginSimple"; } /** * 請求接收的是一個Java類 * @param person * @return */ @ResponseBody @OpLogger(id = "18633334444", type=OpType.SEARCH) @RequestMapping(value="/getForm", method=RequestMethod.POST) public BaseJsonRst<List<Person>> getForm(Person person, @RequestParam("currentPage") int currentPage){ log.info("\r\nid: "+person.getId()+", name: "+person.getName()+", currentPage: "+currentPage); BaseJsonRst<List<Person>> ret = new BaseJsonRst<List<Person>>(); List<Person> list = CreatMockData.createPersonList(20,currentPage); ret.setResult(list); ret.setTotalCounts(250); ret.setCurrentPage(person.getCurrentPage()); ret.setSuccess(true); return ret; } private Exception Exception(String string) { // TODO Auto-generated method stub return null; } public static void main(String[] args){ int a = (int)Math.ceil(1.002); System.out.println(a); } }
jsp檔案:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path; %> <html> <head> <title>jquery.form.js用法- author: paincupid</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <script type="text/javascript" src="<%=basePath%>/resources/js/jquery/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="<%=basePath%>/resources/js/jqueryForm/jquery.form.js"></script> <!-- selene theme --> <script type="text/javascript" src="<%=basePath%>/resources/js/seleneJs/html5.js"></script> <script type="text/javascript" src="<%=basePath%>/resources/js/seleneJs/jquery-ui.min-1.8.16.js"></script> <link type="text/css" href="<%=basePath%>/resources/css/seleneTheme/css/ui-selene/jquery-ui-1.8.17.custom.css" rel="stylesheet" /> <link rel="stylesheet" href="<%=basePath%>/resources/css/seleneTheme/site/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8"> <!-- jqPaginator --> <script type="text/javascript" src="<%=basePath%>/resources/js/jqPaginator/jqPaginator.js"></script> <!-- <link type="text/css" rel="stylesheet" href="http://cdn.staticfile.org/twitter-bootstrap/3.1.1/css/bootstrap.min.css"/> --> <script type="text/javascript"> $(function(){ serach(1); $("#search_btn1").click(function () { serach(1); }); }); function serach(currentPage){ $("#currentPage").val(currentPage); $("#searchForm1").ajaxSubmit({ url :'${pageContext.request.contextPath}/jqueryFormPluginSimple/getForm', //預設是form的action,如果申明,則會覆蓋 type : "POST", // 預設值是form的method("GET" or "POST"),如果宣告,則會覆蓋 dataType : "json", // html(預設)、xml、script、json接受伺服器端返回的型別 beforeSubmit : function(){ // 提交前的回撥函式,做表單校驗用 $("#name").val("lee李 - beforeSubmit"); $("#comment").val("呵呵ll123"); return true; }, beforeSerialize: function(){ //提交到Action/Controller時,可以自己對某些值進行處理。 $("#id").val("lele李"); $("#name").val("lee李 - beforeSerialize"); $("#comment").val("呵呵ll123444"); }, success: function(data){ if (data.success == true) { buildTableData(data); initPageWidget(data); }else{ alert("error:"+data.responseText); } } }); } function buildTableData(data){ var retlist = data.result; $(".retListTr").remove(); for (var i = 0; i < retlist.length; i++) { var vo = retlist[i]; var tbodyString = "<tr class = 'retListTr' data-id=" + vo.id +">"; tbodyString = tbodyString + '<td>' + (i + 1) + '</td>' + '<td>' + vo.id + '</td>' + '<td>' + vo.name + '</td>' + '<td>' + vo.age + '</td>' + '<td>' + vo.tel + '</td>' + '<td>' + vo.prov + '</td>' + '<td>' + vo.city + '</td>' + '<td>' + vo.town + '</td>' + '<td>' + vo.sex + '</td>' + '<td>' + vo.location + '</td>' + '<td>' + vo.company + '</td>' + '<td>' + vo.comment + '</td>'; tbodyString = tbodyString + "</tr>"; $("#retListBody").append($(tbodyString)); } } function initPageWidget(data){ //jqPaginator初始化 $.jqPaginator('#pagination', { visiblePages: 10, currentPage: data.currentPage, pageSize: data.pageSize, totalCounts: data.totalCounts, onPageChange: function (num, type) { if(type=="init") return; serach(num); } }); } </script> </head> <body> <div class="container"> <div class="content" > <div style="padding-left:2%"> <h2>jquery.form.js用法</h2> </div> <form name="searchForm1" id="searchForm1" enctype="multipart/form-data"> <input type="hidden" name="comment" id="comment" value="123" style="width: 800px; height: 400px"/> <input type="hidden" name="currentPage" id="currentPage"/> <div class="component" > <label style="width:24%;">pid</label> <input id = "id" name="id" class="text" type = "text" value="18600001234"/> <label style="width:24%;">姓名</label> <input id = "name" name="name" class="text" type = "text" value="用jqueryFormPlugin的提交"/> <button id="search_btn1" type="button" class="buttons ui-button-blue ui-button ui-widget ui-state-default ui-corner-all">查詢提交表單1</button> </div> </form> <div class="space"></div> <table class="listTable" id = "retListTable" > <thead> <tr> <th scope="col">序號</th> <th scope="col">id</th> <th scope="col">姓名</th> <th scope="col">年齡</th> <th scope="col">電話</th> <th scope="col">省</th> <th scope="col">市</th> <th scope="col">區</th> <th scope="col">性別</th> <th scope="col">地點</th> <th scope="col">公司</th> <th scope="col">備註</th> </tr> </thead> <tbody id = "retListBody" > </tbody> </table> <div style="float:right; padding-right:2%"> <ul class="pagination" id="pagination"></ul> </div> </div><!-- content end --> </div><!-- container end --> </body> </html>
pom.xml
<!-- spring support jason by jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<!-- spring support jason by jackson end -->