【问题标题】:How to get a simple String from Action to JSP with Struts?如何使用 Struts 从 Action 获取简单的 String 到 JSP?
【发布时间】:2017-01-26 11:28:09
【问题描述】:

我有这个问题:我需要从 Action 中获取一些简单的数据并发送回 JSP(已经加载),所以我必须管理 action 以使用 jQuery $.ajax 方法恢复该数据。所以这是我的代码:

MyAction.java

private String employee;
private InputStream inputStreamEmployee;
//these with getter/setter

public String someData() throws Exception{
        employee= "John Doe";
        inputStreamEmployee = new ByteArrayInputStream(
                  employee.getBytes(StandardCharsets.UTF_8)); 

        return "SUCCESS";
    }

struts.xml

<action name="getSomeData" method="someData" class="MyAction">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStreamEmployee</param>
    </result>
</action>

data.js

function getData(){
    $.ajax({
        type: 'GET',
        url: 'getSomeData',
        dataType: 'text',
        async: true,
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert('no data!!');
        }
    });

我检查了这个resource,但我需要 javascript 部分。所以我调试并检查了开发。 javascript方法调用java中的action,action返回success,但是function(data)中的data没有正确获取InputStream,只是获取了整个html网页源,如图:

我做错了什么?提前致谢。

【问题讨论】:

标签: java jquery ajax jsp struts2


【解决方案1】:

忘记 javascript 调用,您的问题是请求 www.yourdomain.com/getSomeData 没有返回带有文本 John Doe 的页面。

为什么要使用 inputStream?如果您使用 JSP 作为模板系统,一个简单的解决方案是

MyAction.java

private String employee;

public String someData() throws Exception{
    employee= "John Doe";
    return "SUCCESS";
}


public String getEmployee(){
    return employee;
}

stuts.xml

<action name="getSomeData" method="someData" class="MyAction">
    <result>/WEB-INF/.../templates/some_data.jsp</result>
</action>

some_data.jsp

<%= employee%>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2013-05-07
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多