您的位置:首页 > 编程语言 > Java开发

struts2:JSON在struts中的应用(JSP页面中将对象转换为JSON字符串提交、JSP页面中获取后台Response返回的JSON对象)

2013-12-06 15:23 946 查看
JSON主要创建如下两种数据对象:

由JSON格式字符串创建,转换成JavaScript的Object对象;

由JSON格式字符串创建,转换成JavaScript的List或数组链表对象。

更多关于JSON的信息,请参考:JSON概述及其在JavaScript与Java中的应用(整理)

1. JSP页面中将对象转换为JSON字符串提交

1.1 创建JSP文件(convertObject2Json.jsp)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="../../js/json2.js">
</script>
<script type="text/javascript">
function ajaxTransferText(){
var BigText = document.getElementById("BigText").value;
var ajaxTransferObjectRef = new ajaxTransferObject("张三", "密码11", 10, BigText);
var JSONString = JSON.stringify(ajaxTransferObjectRef);

if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
myAjaxObject = new XMLHttpRequest();
}

var urlString = "jsonString=" + JSONString;

alert(urlString);
myAjaxObject.open("POST", "postJson.action"+"?timestamp=" + new Date().getTime(), true);
myAjaxObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

myAjaxObject.send(urlString);
}

function ajaxTransferObject(username, password, age, BigText){
this.username = username;
this.password = password;
this.age = age;
this.BigText = BigText;
}
</script>
</head>
<body>
<textarea name="textarea" id="BigText" cols="45" rows="5">需要提交的信息主体...</textarea>
<br/>
<input type="button" value="提交试试" onclick="ajaxTransferText()"/>
</body>
</html>


1.2 创建后台处理Action类

package com.clzhang.ssh.demo6;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;

/**
* 获取前台提交的JSON数据
* @author Administrator
*
*/
public class PostJSONAction extends ActionSupport {
public static final long serialVersionUID = 1;

private String jsonString;

public String getJsonString() {
return jsonString;
}

public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}

public String execute() {
System.out.println(jsonString);

JSONObject json = JSONObject.fromObject(jsonString);
System.out.println("username=" + json.get("username"));
System.out.println("username=" + json.get("password"));
System.out.println("username=" + json.get("age"));
System.out.println("username=" + json.get("BigText"));

return null;
}
}


1.3 修改配置文件struts.xml

<action name="postJson" class="com.clzhang.ssh.demo6.PostJSONAction">
</action>


1.4 测试

打开IE,输入地址:http://127.0.0.1:8080/st/ssh/demo6/convertObject2Json.jsp

结果如下:

package com.clzhang.ssh.demo6;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
* 返回给前台JSON数据,以四种方式
* @author Administrator
*
*/
public class ReturnJSONAction extends ActionSupport {
public static final long serialVersionUID = 1;

private List<String> lstString = new ArrayList<String>();

public ReturnJSONAction() {
lstString.add("你今天吃了吗?");
lstString.add("吃了多吃点");
lstString.add("没吃回家吃去");
lstString.add("好好学习");
lstString.add("天天向上");
}

public String listString() throws IOException {
JSONArray json = JSONArray.fromObject(lstString);
System.out.println(json.toString());

ServletActionContext.getResponse().setContentType("text/html");
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().getWriter().printf(json.toString());
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();

return null;
}

public String listBean() throws IOException {
List<UserInfo> listBean = new ArrayList<UserInfo>();

for(String str: lstString) {
UserInfo userInfo1 = new UserInfo();
userInfo1.setUsername(str);
userInfo1.setPassword("P" + Math.random());
userInfo1.setAge((int)(Math.random()*10));
userInfo1.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss")
.format(new Date()));

listBean.add(userInfo1);
}

JSONArray json = JSONArray.fromObject(listBean);
System.out.println(json.toString());

ServletActionContext.getResponse().setContentType("text/html");
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().getWriter().printf(json.toString());
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();

return null;
}

public String mapString() throws Exception {
LinkedHashMap<String, String> mapString = new LinkedHashMap<String, String>();
int count = 1;
for(String str: lstString) {
mapString.put(""+count++, str+count);
}

JSONArray json = JSONArray.fromObject(mapString);
System.out.println(json.toString());

ServletActionContext.getResponse().setContentType("text/html");
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().getWriter().printf(json.toString());
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();

return null;
}

public String mapBean() throws Exception {
LinkedHashMap<String, UserInfo> mapString = new LinkedHashMap<String, UserInfo>();

int count = 1;
for(String str: lstString) {
UserInfo userInfo1 = new UserInfo();
userInfo1.setUsername(str);
userInfo1.setPassword("P" + Math.random());
userInfo1.setAge((int)(Math.random()*10));
userInfo1.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss")
.format(new Date()));

mapString.put(""+count++, userInfo1);
}

JSONArray json = JSONArray.fromObject(mapString);
System.out.println(json.toString());

ServletActionContext.getResponse().setContentType("text/html");
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().getWriter().printf(json.toString());
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();

return null;
}

public String execute() throws IOException {
return null;
}
}


View Code

2.3 修改配置文件struts.xml

<action name="getJson" class="com.clzhang.ssh.demo6.ReturnJSONAction">
</action>


2.4 测试

打开IE,输入地址:http://127.0.0.1:8080/st/ssh/demo6/getJsonFromResp.jsp

2.4.1 按下“返回List中存String类型的JSON”按钮





2.4.2 按下“返回List中存Bean类型的JSON”按钮



2.4.3 按下“返回Map中存String类型的JSON”按钮



2.4.4 按下“返回Map中存Bean类型的JSON”按钮

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐