springmvc框架写到现在终于牵扯到小程序了(所以别说我“不务正业”),对于一个应用程序来说,它的本质其实就是无数个对数据进行增删改查的操作,这里起到至关重要的就是数据,于是这篇帖子的目的就是实现小程序与后台数据的交互。
小程序使用的是wx.request的api来提交和接收数据,最常见的就是接收后台传过来的json数据,并对其进行解析
先看运行结果:
这里总结springmvc框架的三种转json方法
后台 | 前台 | 返回前台的json格式 |
对象/bean/实体类 | json | {“id”: 0,”username”: “”,”age”: 0} |
List<实体类> | json | [{“id”:1,”username”:”2”,”age”:1},{“id”:2,”username”:”3”,”age”:2}] |
Map<String,实体类> | json | {“success”:true,”detail”:[ ] } |
按步骤,从头开始来:
后台
web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <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">
3. <servlet>
4. <servlet-name>springmvc</servlet-name>
5. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
6. <init-param>
7. <param-name>contextConfigLocation</param-name>
8. <param-value>classpath:config/ybajax.xml</param-value>
9. </init-param>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>springmvc</servlet-name>
13. <url-pattern>*.mn</url-pattern>
14. </servlet-mapping>
15. <filter>
16. <filter-name>CharacterEncodingFilter</filter-name>
17. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
18. <init-param>
19. <param-name>encoding</param-name>
20. <param-value>UTF-8</param-value>
21. </init-param>
22. </filter>
23. <filter-mapping>
24. <filter-name>CharacterEncodingFilter</filter-name>
25. <url-pattern>/*</url-pattern>
26. </filter-mapping>
27. </web-app>
导入springmvc所需要的jar包:http://pan.baidu.com/s/1jIK6sb8导入json所需要的jar包:http://pan.baidu.com/s/1i5bnggP
配置文件 ybajax.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:mvc="http://www.springframework.org/schema/mvc"
6. xmlns:context="http://www.springframework.org/schema/context"
7. xsi:schemaLocation="http://www.springframework.org/schema/beans
8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
9. http://www.springframework.org/schema/mvc
10. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
11. http://www.springframework.org/schema/context
12. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
13. <context:component-scan base-package="action"/>
14. <!-- 注册适配器 -->
15. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
16. <property name="messageConverters">
17. <list>
18. <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
19. </list>
20. </property>
21. </bean>
22. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
23. <property name="prefix" value="/jsp/"/>
24. <property name="suffix" value=".jsp"/>
25. </bean>
26. </beans>
注意json需要对应的适配器类
实体类:User.java (实现bean用到)和 Bean.java(实现List、Map用到)
1. package bean;
2. public class User {
3. private int id;
4. private String username;
5. private int age;
6. public User() {}
7. public User(int id, String username, int age) {
8. this.id = id;
9. this.username = username;
10. this.age = age;
11. }
12. public int getId() {
13. return id;
14. }
15. public void setId(int id) {
16. this.id = id;
17. }
18. public String getUsername() {
19. return username;
20. }
21. public void setUsername(String username) {
22. this.username = username;
23. }
24. public int getAge() {
25. return age;
26. }
27. public void setAge(int age) {
28. this.age = age;
29. }
30. }
31.
32. package bean;
33. import java.util.ArrayList;
34. import java.util.List;
35. public class Bean {
36. private List<User> listuser= new ArrayList<User>();
37. private Bean(){}
38. public List<User> getListuser() {
39. return listuser;
40. }
41. public void setListuser(List<User> listuser) {
42. this.listuser = listuser;
43. }
44. }
AjaxAction.java
1. package action;
2. import java.util.ArrayList;
3. import java.util.HashMap;
4. import java.util.List;
5. import java.util.Map;
6. import org.springframework.stereotype.Controller;
7. import org.springframework.ui.Model;
8. import org.springframework.web.bind.annotation.RequestBody;
9. import org.springframework.web.bind.annotation.RequestMapping;
10. import org.springframework.web.bind.annotation.RequestMethod;
11. import org.springframework.web.bind.annotation.ResponseBody;
12. import bean.Bean;
13. import bean.User;
14. @Controller
15. @RequestMapping("/user")
16. public class YbAjaxAction{
17. @RequestMapping(method=RequestMethod.POST,value="/bean2json")
18. public @ResponseBody User bean2json(User user){
19. return user;
20. }
21. @RequestMapping(method=RequestMethod.POST,value="/listbean2json")
22. public @ResponseBody List<User> listbean2json(Bean bean){
23. List<User> listuser=bean.getListuser();
24. return listuser;
25. }
26. @RequestMapping(method=RequestMethod.POST,value="/mapbean2json")
27. public @ResponseBody Map<String,Object> mapbean2json(Bean bean){
28. List<User> listuser=bean.getListuser();
29. Map<String, Object> mapuser=new HashMap<String, Object>();
30. mapuser.put("success",true);
31. mapuser.put("detail",listuser);
32. return mapuser;
33. }
34. //表单提交
35. @RequestMapping(method=RequestMethod.POST,value="/json2json")
36. public @ResponseBody User bean2json(@RequestBody Map<String, String> map){
37. String username="";
38. int age=0;
39. if(map.containsKey("username")){
40. username=map.get("username");
41. }
42. if(map.containsKey("age")){
43. age=Integer.parseInt(map.get("age"));
44. }
45. User user=new User(1,username,age);
46. return user;
47. }
48. }
@ResponseBody: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区(用于返回json数据给页面)
@RequestBody
前台
index.wxml
1. <view class="container">
2. <button bindtap="bean_json" class="btn">bean_json</button>
3. <button bindtap="listbean_json" class="btn">listbean_json</button>
4. <button bindtap="mapbean_json" class="btn">mapbean_json</button>
5. <view class="line"></view>
6. <form bindsubmit="json_json">
7. <view>
8. <view >username</view>
9. <input name="username" type="text" class="input_bg"/>
10. </view>
11. <view>
12. <view >age</view>
13. <input name="age" type="text" class="input_bg"/>
14. </view>
15. <button formType="submit" class="btn">json_json</button>
16. </form>
17. <text>{{show}}</text>
18. </view>
index.wxss
1. .container {
2. height: 100%;
3. display: flex;
4. flex-direction: column;
5. padding: 20rpx;
6. }
7. .input_bg{
8. background-color: #F8F8F8;
9. border-radius: 10rpx;
10. }
11. .btn{
12. background-color: #A65353;
13. margin: 20rpx;
14. border-radius: 10rpx;
15. color:#F8F8F8;
16. }
17. .line{
18. height: 1rpx;
19. width: 100%;
20. background-color: #A65353;
21. margin: 30rpx 0;
22. }
index.js
1. var app = getApp()
2. Page({
3. data: {
4. show:""
5. },
6. bean_json: function() {
7. var that=this;
8. wx.request({
9. url: 'http://localhost:8080/springMVC/user/bean2json.mn',
10. data: {
11. id:1,
12. username:"toBeMN",
13. age:28
14. },
15. method: 'POST',
16. header: {
17. "Content-Type":"application/x-www-form-urlencoded"
18. },
19. success: function(res){
20. var show="对象转json
21. username:"+res.data.username+
22. "
23. age:"+res.data.age;
24. that.setData({
25. show:show
26. })
27. }
28. })
29. },
30. listbean_json: function() {
31. var that=this;
32. wx.request({
33. url: 'http://localhost:8080/springMVC/user/listbean2json.mn',
34. data: {
35. 'listuser[0].username':"Hello",
36. 'listuser[0].age':18,
37. 'listuser[1].username':"World",
38. 'listuser[1].age':28
39. },
40. method: 'POST',
41. header: {
42. "Content-Type":"application/x-www-form-urlencoded"
43. },
44. success: function(res){
45. var show="list<对象>转json ";
46. for(var i=0;i<res.data.length;i++){
47. show+="
48. username:"+res.data[i].username+
49. "
50. age:"+res.data[i].age;
51. }
52. that.setData({
53. show:show
54. })
55. }
56. })
57. },
58. mapbean_json: function() {
59. var that=this;
60. wx.request({
61. url: 'http://localhost:8080/springMVC/user/mapbean2json.mn',
62. data: {
63. 'listuser[0].username':"Hello",
64. 'listuser[0].age':48,
65. 'listuser[1].username':"MINA",
66. 'listuser[1].age':58
67. },
68. method: 'POST',
69. header: {
70. "Content-Type":"application/x-www-form-urlencoded"
71. },
72. success: function(res){
73. var show="map<String,Obiect>转json ";
74. for(var i=0;i<res.data.detail.length;i++){
75. show+="
76. username:"+res.data.detail[i].username+
77. "
78. age:"+res.data.detail[i].age;
79. }
80. that.setData({
81. show:show
82. })
83. }
84. })
85. },
86. json_json: function(res) {
87. var that=this;
88. console.log(res.detail.value)
89. wx.request({
90. url: 'http://localhost:8080/springMVC/user/json2json.mn',
91. data: res.detail.value,
92. method: 'POST',
93. header: {
94. "Content-Type":"application/json"
95. },
96. success: function(res){
97. var show="表单提交返回json
98. username:"+res.data.username+
99. "
100. age:"+res.data.age;
101. that.setData({
102. show:show
103. })
104. }
105. })
106. },
107. onLoad: function () {
108. }
109. })
所有的映射处理都交由框架,我们只需要设置对的属性名、变量名,即可自动赋值
例如表单提交,这个应该是最常用的,因为小程序form提交后会将表单中的数据存入一个json串(如果表单中input的name没有写,则不会有数据,这是小程序内部映射的神奇之处),所以使用request请求的时候可以直接将json串传到后台解析,后台处理完业务在将结果json传回前台,这就是一个交互的过程。