13.向页面返回字符串或者对象

 

项目目录结构:

  1. WebContent/easyui/: easyui库
  2. WebContent/js/: jquery库
  3. WebContent/json/: easyui的datagrip组件接收的示例json数据

项目依赖包:

Vo: User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.course.vo;

public class User {

private Integer id;
private String name;
private Integer age;

public User() {
super();
}

public User(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}

Vo: UserInfo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.course.vo;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

public class UserInfo {

private Integer id;
private String name;
private Integer age;
private String address;
// 前端->后端: 时间类型格式转换
@DateTimeFormat(pattern = "yyyy-MM-dd")
// 后端->前端: 时间类型格式转换,使用Jackson生成json对象时把时间进行格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date time;

public UserInfo() {
super();
}

public UserInfo(Integer id, String name, Integer age, String address, Date time) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.time = time;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Date getTime() {
return time;
}

public void setTime(Date time) {
this.time = time;
}

@Override
public String toString() {
return "UserInfo [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", time=" + time
+ "]";
}

}

DataGripObject.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.course.util;

import java.util.List;

public class DataGripObject {

private long total;
private List<?> rows;

public DataGripObject() {
super();
}

public DataGripObject(long total, List<?> rows) {
super();
this.total = total;
this.rows = rows;
}

public long getTotal() {
return total;
}

public void setTotal(long total) {
this.total = total;
}

public List<?> getRows() {
return rows;
}

public void setRows(List<?> rows) {
this.rows = rows;
}

}

UserController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package com.course.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

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.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.course.util.DataGripObject;
import com.course.vo.User;
import com.course.vo.UserInfo;

@Controller
@RequestMapping("user")
public class UserController {

static List<String> usernameList = new ArrayList<>();

static {
usernameList.add("admin");
usernameList.add("user1");
usernameList.add("user2");
}

// 检查用户名是否存在
@RequestMapping(value = "checkUserName1", method = RequestMethod.POST)
public void checkUserName1(String username, HttpServletResponse httpServletResponse) {
String message = "该用户不存在";
for (String nameItem : usernameList) {
if (nameItem.equals(username)) {
message = "该用户存在";
}
}
try {
// 处理乱码
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("text/html;charset=utf-8");

PrintWriter out = httpServletResponse.getWriter();
out.write(message);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

@RequestMapping(value = "checkUserName2", method = RequestMethod.POST)
@ResponseBody
public String checkUserName2(String username) {
String code = "0";
for (String nameItem : usernameList) {
if (nameItem.equals(username)) {
code = "1";
}
}
return code;
}

@RequestMapping(value = "getOneUser1", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@ResponseBody
public String getOneUser1() {
User user = new User();
user.setId(1);
user.setName("小明");
user.setAge(10);
String json = JSONObject.toJSONString(user);
return json;
}

@RequestMapping(value = "getUserList1", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@ResponseBody
public String getUserList1() {
List<User> userList = new ArrayList<>();
userList.add(new User(1, "小明", 10));
userList.add(new User(2, "小李", 11));
userList.add(new User(3, "小张", 12));
String json = JSONObject.toJSONString(userList);
return json;
}

/*
* 1.引入jackson的相关jar包:
* (1)jackson-annotations-2.8.9.jar
* (2)jackson-core-2.8.9.jar
* (3)jackson-databind-2.8.9.jar
* 2.springmvc.xml配置文件添加相应的配置
* <mvc:annotation-driven></mvc:annotation-driven>
*/
@RequestMapping(value = "getOneUser2", method = RequestMethod.GET)
@ResponseBody
public User getOneUser2() {
User user = new User();
user.setId(1);
user.setName("小明");
user.setAge(10);
return user;
}

@RequestMapping(value = "getUserList2", method = RequestMethod.GET)
@ResponseBody
public List<User> getUserList2() {
List<User> userList = new ArrayList<>();
userList.add(new User(1, "小明", 10));
userList.add(new User(2, "小李", 11));
userList.add(new User(3, "小张", 12));
return userList;
}

/*
* 返回json对象: Map
* @RequestMapping不添加method属性,表示该方法GET和POST请求都接收
*/
@RequestMapping(value = "getUserList3")
@ResponseBody
public Map<String, Object> getUserList3() {
Map<String, Object> resultMap = new HashMap<>();

List<UserInfo> userList = new ArrayList<>();
userList.add(new UserInfo(1, "小明", 10, "address1", new Date()));
userList.add(new UserInfo(2, "小李", 11, "address2", new Date()));
userList.add(new UserInfo(3, "小张", 12, "address3", new Date()));

resultMap.put("total", userList.size());
resultMap.put("rows", userList);

return resultMap;
}

/*
* 返回json对象: Object
* @RequestMapping不添加method属性,表示该方法GET和POST请求都接收
*/
@RequestMapping(value = "getUserList4")
@ResponseBody
public DataGripObject getUserList4() {
DataGripObject dataGripObject = new DataGripObject();

List<UserInfo> userList = new ArrayList<>();
userList.add(new UserInfo(1, "user1", 10, "address1", new Date()));
userList.add(new UserInfo(2, "user2", 11, "address2", new Date()));
userList.add(new UserInfo(3, "user3", 12, "address3", new Date()));

dataGripObject.setTotal(userList.size());
dataGripObject.setRows(userList);

return dataGripObject;
}

}

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=INFO, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<!--
配置控制器
包扫描
-->
<context:component-scan base-package="com.course.controller"></context:component-scan>

<!--
合并注解的控制器映射器和控制器适配器的配置
对控制器映射器和控制器适配器进行加强,如把对象转化为json字符串
-->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

</beans>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?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">
<display-name>01_springmvc_hello</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<!-- 配置SpringMVC编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!--
方法1: <url-pattern>*.do</url-pattern>
<url-pattern>/*</url-pattern>
-->
<!-- 指定某个servlet去过滤 -->
<servlet-name>springmvc</servlet-name>
</filter-mapping>

<!-- 配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 加载springmvc.xml -->
<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>

</web-app>

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>检查用户名是否存在</h2>
<p>
name: <input type="text" name="username" id="username">
<label id="tip"></label>
</p>
</body>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#username").blur(function(){
var username = $(this).val();
var url = "user/checkUserName1.do";
$.post(url, {"username": username}, function(message) {
alert(message);
});
url = "user/checkUserName2.do";
$.post(url, {"username": username}, function(code) {
if (code == "0") {
$("#tip").html('<font color="blue">该用户不存在</font>');
} else {
$("#tip").html('<font color="blue">该用户存在</font>');
}
});
});

});
</script>

</html>

userList.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/metro/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/demo/demo.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<h2 align="center">所有用户</h2>
<table id="dg" title="所有用户" iconCls="icon-help" class="easyui-datagrid" style="width:100%;height:550px"
url="${pageContext.request.contextPath}/user/getUserList4.do"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="id" width="50" align="center">ID</th>
<th field="name" width="50">姓名</th>
<th field="age" width="50">年龄</th>
<th field="address" width="50">地址</th>
<th field="time" width="50">生日</th>
</tr>
</thead>
</table>
<div id="toolbar">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加用户</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">修改用户</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">删除用户</a>
</div>
</body>
</html>

浏览器访问