struts 返回字符串2怎么返回一个字符串给jsp

JSON主要创建如下两种数据对象:
由JSON格式字符串创建,转换成JavaScript的Object对象;
由JSON格式字符串创建,转换成JavaScript的List或数组链表对象。
更多关于JSON的信息,请参考:
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"&
&meta http-equiv="Content-Type" content="text/ charset=utf-8"&
&script type="text/javascript" src="../../js/json2.js"&
&script type="text/javascript"&
function ajaxTransferText(){
var BigText = document.getElementById("BigText").
var ajaxTransferObjectRef = new ajaxTransferObject("张三", "密码11", 10, BigText);
var JSONString = JSON.stringify(ajaxTransferObjectRef);
if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
myAjaxObject = new XMLHttpRequest();
var urlString = "jsonString=" + JSONS
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 =
this.password =
this.age =
this.BigText = BigT
&textarea name="textarea" id="BigText" cols="45" rows="5"&需要提交的信息主体...&/textarea&
&input type="button" value="提交试试" onclick="ajaxTransferText()"/&
1.2 创建后台处理Action类
package com.clzhang.ssh.demo6;
import net.sf.json.JSONO
import com.opensymphony.xwork2.ActionS
* 获取前台提交的JSON数据
* @author Administrator
public class PostJSONAction extends ActionSupport {
public static final long serialVersionUID = 1;
private String jsonS
public String getJsonString() {
return jsonS
public void setJsonString(String jsonString) {
this.jsonString = jsonS
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"&
打开IE,输入地址:
结果如下:
确定后,后台显示:
2. JSP页面获取后台Response返回的JSON对象
2.1 创建JSP文件(getJsonFromResp.jsp)
&%@ page language="java" import="java.util.*" pageEncoding="utf-8" %&
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&meta http-equiv="Content-Type" content="text/ charset=utf-8"&
&script type="text/javascript" src="../../js/json2.js"&
&script type="text/javascript"&
var myAjaxO
//在List中存字符串
function getListString(){
if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
myAjaxObject = new XMLHttpRequest();
myAjaxObject.open("GET", "getJson!listString.action?date=" + new Date().getTime(), true);
myAjaxObject.onreadystatechange = retrunListS
myAjaxObject.send();
function retrunListString(){
if (myAjaxObject.readyState == 4) {
if (myAjaxObject.status == 200) {
var returnJSONString = myAjaxObject.responseT
var returnJSON = JSON.parse(returnJSONString);
var showString = "";
for (var i = 0; i & returnJSON. i++) {
showString = showString + returnJSON[i] + " ";
alert(showString);
//在List中存Bean
function getListBean(){
if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
myAjaxObject = new XMLHttpRequest();
myAjaxObject.open("GET", "getJson!listBean.action?date=" + new Date().getTime(), true);
myAjaxObject.onreadystatechange = retrunListB
myAjaxObject.send();
function retrunListBean(){
if (myAjaxObject.readyState == 4) {
if (myAjaxObject.status == 200) {
var returnJSONString = myAjaxObject.responseT
var returnJSON = JSON.parse(returnJSONString);
var showString = "";
for (var i = 0; i & returnJSON. i++) {
showString = showString + returnJSON[i].username + " " + returnJSON[i].password + " " + returnJSON[i].age + " " + returnJSON[i].createDate + "\n";
alert(showString);
//在Map中存字符串
function getMapString(){
if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
myAjaxObject = new XMLHttpRequest();
myAjaxObject.open("GET", "getJson!mapString.action?date=" + new Date().getTime(), true);
myAjaxObject.onreadystatechange = retrunMapS
myAjaxObject.send();
function retrunMapString(){
if (myAjaxObject.readyState == 4) {
if (myAjaxObject.status == 200) {
var returnJSONString = myAjaxObject.responseT
var returnJSON = JSON.parse(returnJSONString);
var showString = "";
for (var i in returnJSON[0]) {
showString = showString + "key=" + i + " value=" + returnJSON[0][i] + "\n";
alert(showString);
//在Map中存Bean
function getMapBean(){
if (window.ActiveXObject) {
myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
myAjaxObject = new XMLHttpRequest();
myAjaxObject.open("GET", "getJson!mapBean.action?date=" + new Date().getTime(), true);
myAjaxObject.onreadystatechange = retrunMapB
myAjaxObject.send();
function retrunMapBean(){
if (myAjaxObject.readyState == 4) {
if (myAjaxObject.status == 200) {
var returnJSONString = myAjaxObject.responseT
var returnJSON = JSON.parse(returnJSONString);
var showString = "";
for (var i in returnJSON[0]) {
showString = showString + "key=" + i + " username=" + returnJSON[0][i].username + " password=" + returnJSON[0][i].password + " age=" + returnJSON[0][i].age + " createDate=" + returnJSON[0][i].createDate + "\n";
alert(showString);
&input type="button" value="返回List中存String类型的JSON" onclick="getListString()"/&
&input type="button" value="返回List中存Bean类型的JSON" onclick="getListBean()"/&
&input type="button" value="返回Map中存String类型的JSON" onclick="getMapString()"/&
&input type="button" value="返回Map中存Bean类型的JSON" onclick="getMapBean()"/&
2.2 创建后台处理Action类
package com.clzhang.ssh.demo6;
import java.io.IOE
import java.text.SimpleDateF
import java.util.*;
import net.sf.json.JSONA
import org.apache.struts2.ServletActionC
import com.opensymphony.xwork2.ActionS
* 返回给前台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;
2.3 修改配置文件struts.xml
&action name="getJson" class="com.clzhang.ssh.demo6.ReturnJSONAction"&
打开IE,输入地址:
2.4.1 按下&返回List中存String类型的JSON&按钮
2.4.2 按下&返回List中存Bean类型的JSON&按钮
2.4.3 按下&返回Map中存String类型的JSON&按钮
2.4.4 按下&返回Map中存Bean类型的JSON&按钮
阅读(...) 评论()我们都知道使用servlet时可以直接用PrintWriter对象的print方法来向页面传送一些字符串(可以是html标签和内容),然后在用RequestDispatcher来转向网页
虽Struts2的Action返回的也是字然符串,但是这个字符串并不是将这个字符串传给网页,实际上它映射到一个物理视图的,也就是网页。
那么怎么让Struts2返回一个字符串呢?&&使用JSON
在Struts2的lib下有个struts2-json-plugin-version.jar,将其复制到WEB-INF/lib下,如果使用了eclipse,还得右键-&Buld Path-&add to buil path
然后配置action:
/****方式一 添加注解:****/
@ParentPackage(value="json-default")
@Result(type="json", params={"noCache", "true", "contentType", "text/html"})
/****方式二 配置struts.xml***/
&package extends="json-default"&
&action name="notice" class="com.xxx.action.NoticeAction"&
&result type="json"&
&param name="noCache"&true&/param&
&param name="contentType"&text/html&/param&
&/package&
其中noCache这个属性设置&是否取消浏览器缓存&,改为true将增加文件头。
父包json-default是死的。
配置结果为json后,execute的返回值没有了任何意义
那么这个json的内容是什么?
实际上,struts2会将该action中getter的名字/返回值 当作json 的键/值。
如: 你的action中有个String getContent()方法,返回值是"哈哈",那么生成的json字符串为:{"content":"哈哈"}
要注意的是,即使你没有content这个属性,也能生成对应的json
&然后在JSP画面,使用jquery发送/接收请求(JSON.parse需要下载JSON.js):
$(document).ready(function() {
$.get("notice",
function(json) {
$("#cc").html(JSON.parse(json).content);
阅读(...) 评论()Struts2登录成功返回一个jsp页面,失败返回一个json字符串遇到的
在做一个登录模块 action代码 配置文件 ajax代码 具体是这样,利用ajax向服务器提交请求,如果验证正确,返回一个jsp页面,再通过Jquery的文档操作$("html").html(data);实现登录成功页面的跳转,失败则返回一个json对象给用户一个友好提示。 测试发现$("htm
在做一个登录模块
action代码
具体是这样,利用ajax向服务器提交请求,如果验证正确,返回一个jsp页面,再通过Jquery的文档操作$("html").html(data);实现登录成功页面的跳转,失败则返回一个json对象给用户一个友好提示。测试发现$("html").html(data);在IE浏览器没效果。。。只是想实现一个登录功能,登录成功即跳转页面,失败则给用户一个友好提示
$("html").html(data);在火狐和UC上测试都没有问题,在IE上就没效果了,data里含有frameset
你最喜欢的在struts2的action中返回数据(普通字符串、xml数据岛字符串等)给ajax核心中的XMLHttpRequest对象
在struts2的action中返回数据(普通字符串、xml数据岛字符串等)给ajax核心中的XMLHttpRequest对象
如何在struts2的action中返回数据(普通字符串、xml数据岛字符串等)给ajax核心中的XMLHttpRequest对象(即模仿传统jsp页面的ajax交互)1、方法:public String execute() throws Exception {String str="xxoohuai";ActionContext.getContext().getResponse().
setContentType("text/charset=UTF-8");&.//使用unicode编码&&
ActionContext.getContext().getResponse()&.getWrite().write("ok");&&&&//这里返回的是null}2、配置struts.xml&action name="BaseInfo" class="controller.hosp.BaseInfoAction"&&&& &result&&/result&&& &/action&ok~~~~~~~~!补充:这样更简单getResponse().getWriter().write("your output String");struts.xml配置连result标签都不用写了
发表评论:
TA的最新馆藏[转]&[转]&[转]&}

我要回帖

更多关于 struts2 返回字符串 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信