如何在apache struts2中获取请求体和响应体? - 使用$ .ajax发布

时间:2017-06-28 08:14:05

标签: java ajax jsp struts2

我使用ajax来调用webservice和struts来获取请求参数。这很好,但是我试图用json来获得响应,或者我只需要从服务器返回成功或失败标志。 这是我的代码.. Ajax部分 index.jsp的

function funcName(str, str1){
    $.ajax({
        url : "${pageContext.request.contextPath}/webservicename",
        type : "post",
        data : {
            'key' : str,
            'Status' : str1
        },
        success : getResponse,
        error : function(xhr) {
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }

    });
}

function getResponse(xhr){
    $("#responseBody").html(xhr);
}

服务webservicename映射到struts.xml中一个名为DataAction的java类中的操作 DataAction.java

public class DataAction implements ServletRequestAware{
    HttpServletRequest httpServletRequest = null;

    @Override
    public void setServletRequest(HttpServletRequest arg0) {
        // TODO Auto-generated method stub
        httpServletRequest = arg0;
    }

    public String execute() {
        String key = httpServletRequest.getParameter("key");
        String status = httpServletRequest.getParameter("status");
        System.out.println(key +" "+ status);
        return "success";
    }

}

直到这里它正在工作,我修改了DataAction类并尝试使用Print writer向响应中写入内容,但它显示以下错误

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

修改后的代码

public class DataAction implements ServletRequestAware, ServletResponseAware{
        HttpServletRequest httpServletRequest = null;
        HttpServletResponse httpServletResponse = null;


@Override
public void setServletRequest(HttpServletRequest arg0) {
    // TODO Auto-generated method stub
        httpServletRequest = arg0;
}



@Override
public void setServletResponse(HttpServletResponse arg0) {
    // TODO Auto-generated method stub
        httpServletResponse = arg0;
}

public String execute() {

    try {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println("hello server");
            writer.flush();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String key = httpServletRequest.getParameter("key");
        String status = httpServletRequest.getParameter("status");
        System.out.println(key +" "+ status);
        return "success";
    }

}

如何获取响应正文以及请求正文?

1 个答案:

答案 0 :(得分:1)

由于您写入了http servlet响应,因此响应已经提交,因此您无法使用任何调度程序结果,例如"success"

但是您可以返回结果NONE以防止在操作后执行结果,并且它可能只是选项。

注意,如果堆栈上有任何其他拦截器,例如工作流拦截器,那么它可能会返回INPUT结果,这也是调度程序结果,应该被排除。