Struts2 JSON转换案例
使用Struts2的过程中,前端经常是异步请求后端的,这时Struts的的后端就需要把数据以JSON字符串格式返回给前端,以便前端可以显示正常的效果。下面演示如何在Struts2的后端应用把结果转换为JSON?
1 导入Struts2的JSON插件包
2 设计User类,用于封装数据
package com.yiidian.domain;
import java.io.Serializable;
/**
* @author 一点教程(yiidian.com)
*/
public class User implements Serializable{
private String name;
private String password;
private String email;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
3 编写Action类,返回数据
package com.yiidian.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.yiidian.domain.User;
/**
* Struts2转换后台数据为Json字符串
* @author 一点教程(yiidian.com)
*/
public class Demo1Action extends ActionSupport{
//这个userList需要转换为Json字符串格式输出到浏览器
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String execute() throws Exception {
userList = new ArrayList<User>();
for(int i = 1;i<=5;i++){
User user = new User();
user.setName("小明"+i);
user.setPassword("123");
user.setEmail("xiaoming"+i+"@yiidian.com");
user.setPhone("13211112222");
userList.add(user);
}
return SUCCESS;
}
}
4 struts.xml继承json-default
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 必须继承json-default包,json-default包是在struts2-json-plugin-2.5.13.jar定义的 -->
<package name="base" extends="json-default" namespace="/">
<action name="demo1" class="com.yiidian.action.Demo1Action">
<!-- 类型必须是json -->
<result type="json">
<!-- root代表输出的是ValueStack的数据 ,userList名称和Action的getUserList的属性名称一致-->
<param name="root">userList</param>
</result>
</action>
</package>
</struts>
5 配置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">
<display-name>ch04_07_struts2_json</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6 访问测试
http://localhost:8080/ch04_07_struts2_json/demo1.action
效果如下:
热门文章
优秀文章