原創(chuàng)聲明:本文為作者原創(chuàng),未經(jīng)允許不得轉(zhuǎn)載,經(jīng)授權(quán)轉(zhuǎn)載需注明作者和出處
springmvc框架寫到現(xiàn)在終于牽扯到小程序了(所以別說我“不務(wù)正業(yè)”),對(duì)于一個(gè)應(yīng)用程序來說,它的本質(zhì)其實(shí)就是無數(shù)個(gè)對(duì)數(shù)據(jù)進(jìn)行增刪改查的操作,這里起到至關(guān)重要的就是數(shù)據(jù),于是這篇帖子的目的就是實(shí)現(xiàn)小程序與后臺(tái)數(shù)據(jù)的交互。
小程序使用的是wx.request的api來提交和接收數(shù)據(jù),最常見的就是接收后臺(tái)傳過來的json數(shù)據(jù),并對(duì)其進(jìn)行解析
先看運(yùn)行結(jié)果:
這里總結(jié)springmvc框架的三種轉(zhuǎn)json方法
后臺(tái) | 前臺(tái) | 返回前臺(tái)的json格式 |
---|---|---|
對(duì)象/bean/實(shí)體類 | json | {“id”: 0,”username”: “”,”age”: 0} |
List<實(shí)體類> | json | [{“id”:1,”username”:”2”,”age”:1},{“id”:2,”username”:”3”,”age”:2}] |
Map<String,實(shí)體類> | json | {“success”:true,”detail”:[ ] } |
按步驟,從頭開始來:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<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:config/ybajax.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.mn</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
導(dǎo)入springmvc所需要的jar包:http://pan.baidu.com/s/1jIK6sb8
導(dǎo)入json所需要的jar包:http://pan.baidu.com/s/1i5bnggP
配置文件 ybajax.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="action"/>
<!-- 注冊(cè)適配器 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
注意json需要對(duì)應(yīng)的適配器類
實(shí)體類:User.java (實(shí)現(xiàn)bean用到)和 Bean.java(實(shí)現(xiàn)List、Map用到)
package bean;
public class User {
private int id;
private String username;
private int age;
public User() {}
public User(int id, String username, int age) {
this.id = id;
this.username = username;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
package bean;
import java.util.ArrayList;
import java.util.List;
public class Bean {
private List<User> listuser= new ArrayList<User>();
private Bean(){}
public List<User> getListuser() {
return listuser;
}
public void setListuser(List<User> listuser) {
this.listuser = listuser;
}
}
AjaxAction.java
package action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 bean.Bean;
import bean.User;
@Controller
@RequestMapping("/user")
public class YbAjaxAction{
@RequestMapping(method=RequestMethod.POST,value="/bean2json")
public @ResponseBody User bean2json(User user){
return user;
}
@RequestMapping(method=RequestMethod.POST,value="/listbean2json")
public @ResponseBody List<User> listbean2json(Bean bean){
List<User> listuser=bean.getListuser();
return listuser;
}
@RequestMapping(method=RequestMethod.POST,value="/mapbean2json")
public @ResponseBody Map<String,Object> mapbean2json(Bean bean){
List<User> listuser=bean.getListuser();
Map<String, Object> mapuser=new HashMap<String, Object>();
mapuser.put("success",true);
mapuser.put("detail",listuser);
return mapuser;
}
//表單提交
@RequestMapping(method=RequestMethod.POST,value="/json2json")
public @ResponseBody User bean2json(@RequestBody Map<String, String> map){
String username="";
int age=0;
if(map.containsKey("username")){
username=map.get("username");
}
if(map.containsKey("age")){
age=Integer.parseInt(map.get("age"));
}
User user=new User(1,username,age);
return user;
}
}
@ResponseBody
: 該注解用于將Controller的方法返回的對(duì)象,通過適當(dāng)?shù)腍ttpMessageConverter轉(zhuǎn)換為指定格式后,寫入到Response對(duì)象的body數(shù)據(jù)區(qū)(用于返回json數(shù)據(jù)給頁面)@RequestBody
: 該注解用于讀取Request請(qǐng)求的body部分?jǐn)?shù)據(jù),使用系統(tǒng)默認(rèn)配置的HttpMessageConverter進(jìn)行解析,然后把相應(yīng)的數(shù)據(jù)綁定到要返回的對(duì)象上;再把HttpMessageConverter返回的對(duì)象數(shù)據(jù)綁定到 controller中方法的參數(shù)上(用于接收前臺(tái)的數(shù)據(jù))
index.wxml
<view class="container">
<button bindtap="bean_json" class="btn">bean_json</button>
<button bindtap="listbean_json" class="btn">listbean_json</button>
<button bindtap="mapbean_json" class="btn">mapbean_json</button>
<view class="line"></view>
<form bindsubmit="json_json">
<view>
<view >username</view>
<input name="username" type="text" class="input_bg"/>
</view>
<view>
<view >age</view>
<input name="age" type="text" class="input_bg"/>
</view>
<button formType="submit" class="btn">json_json</button>
</form>
<text>{{show}}</text>
</view>
index.wxss
.container {
height: 100%;
display: flex;
flex-direction: column;
padding: 20rpx;
}
.input_bg{
background-color: #F8F8F8;
border-radius: 10rpx;
}
.btn{
background-color: #A65353;
margin: 20rpx;
border-radius: 10rpx;
color:#F8F8F8;
}
.line{
height: 1rpx;
width: 100%;
background-color: #A65353;
margin: 30rpx 0;
}
index.js
var app = getApp()
Page({
data: {
show:""
},
bean_json: function() {
var that=this;
wx.request({
url: 'http://localhost:8080/springMVC/user/bean2json.mn',
data: {
id:1,
username:"toBeMN",
age:28
},
method: 'POST',
header: {
"Content-Type":"application/x-www-form-urlencoded"
},
success: function(res){
var show="對(duì)象轉(zhuǎn)json
username:"+res.data.username+
"
age:"+res.data.age;
that.setData({
show:show
})
}
})
},
listbean_json: function() {
var that=this;
wx.request({
url: 'http://localhost:8080/springMVC/user/listbean2json.mn',
data: {
'listuser[0].username':"Hello",
'listuser[0].age':18,
'listuser[1].username':"World",
'listuser[1].age':28
},
method: 'POST',
header: {
"Content-Type":"application/x-www-form-urlencoded"
},
success: function(res){
var show="list<對(duì)象>轉(zhuǎn)json ";
for(var i=0;i<res.data.length;i++){
show+="
username:"+res.data[i].username+
"
age:"+res.data[i].age;
}
that.setData({
show:show
})
}
})
},
mapbean_json: function() {
var that=this;
wx.request({
url: 'http://localhost:8080/springMVC/user/mapbean2json.mn',
data: {
'listuser[0].username':"Hello",
'listuser[0].age':48,
'listuser[1].username':"MINA",
'listuser[1].age':58
},
method: 'POST',
header: {
"Content-Type":"application/x-www-form-urlencoded"
},
success: function(res){
var show="map<String,Obiect>轉(zhuǎn)json ";
for(var i=0;i<res.data.detail.length;i++){
show+="
username:"+res.data.detail[i].username+
"
age:"+res.data.detail[i].age;
}
that.setData({
show:show
})
}
})
},
json_json: function(res) {
var that=this;
console.log(res.detail.value)
wx.request({
url: 'http://localhost:8080/springMVC/user/json2json.mn',
data: res.detail.value,
method: 'POST',
header: {
"Content-Type":"application/json"
},
success: function(res){
var show="表單提交返回json
username:"+res.data.username+
"
age:"+res.data.age;
that.setData({
show:show
})
}
})
},
onLoad: function () {
}
})
所有的映射處理都交由框架,我們只需要設(shè)置對(duì)的屬性名、變量名,即可自動(dòng)賦值
例如表單提交,這個(gè)應(yīng)該是最常用的,因?yàn)樾〕绦騠orm提交后會(huì)將表單中的數(shù)據(jù)存入一個(gè)json串(如果表單中input的name沒有寫,則不會(huì)有數(shù)據(jù),這是小程序內(nèi)部映射的神奇之處),所以使用request請(qǐng)求的時(shí)候可以直接將json串傳到后臺(tái)解析,后臺(tái)處理完業(yè)務(wù)在將結(jié)果json傳回前臺(tái),這就是一個(gè)交互的過程。
如有不理解可以提出,yeah!