struts2 动作类中的 Ajax 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8936661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:07:08  来源:igfitidea点击:

Ajax response in struts2 action class

ajaxjspstruts2

提问by shiva

I am trying to implement ajax in jsp(avoid form submit) using struts2. I used ajax code to pass request via url to struts2 action. But the response from struts2 is not get populated in jap. Its showing "null" value. My code to call a action in jsp using AJAX is as Follows.

我正在尝试使用 struts2 在 jsp(避免表单提交)中实现 ajax。我使用 ajax 代码通过 url 将请求传递给 struts2 操作。但是来自 struts2 的响应没有在 jap 中填充。它显示“空”值。我使用 AJAX 在 jsp 中调用操作的代码如下。

    function ajaxEditFunctionCall(){  
 var xmlHttp;
     var url = "ajaxcall.action?stateName="+frm.stateName.value;  
  try{   
    xmlHttp=new XMLHttpRequest();   
  }catch (e){
      try{ 
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
      }catch (e){ 
          try{  
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
            }catch (e){
                alert("Your browser does not support AJAX!");
                return false;
            }
      }
  }
  alert(1);
  xmlHttp.onreadystatechange = showMessage; 
      alert(2);

  xmlHttp.open("GET", URL, true); 

       alert(3);
       xmlHttp.send(null);  
  }

      function showMessage() { 
       alert("Inside Show Message1");
         alert(xmlhttp.readyState);
             if(xmlhttp.readyState==4)  
            { 
             alert("Inside Show Message2&ReadyState4");
                 alert(xmlhttp.responseText);  
            }  
       }  

   Included following code in Action Class:

public String ajaxcall() throws Exception{

     System.out.println("Inside AjaxCall");
     String errorXml = "This is a Sample to Check";  

     response.setContentType("text/html"); 
     response.setHeader("Cache-Control", "no-cache"); 
         response.setContentType("text/html");   
     response.getWriter().write(errorXml); 

     return null;

}

Code included in Struts.xml:

Struts.xml 中包含的代码:

  <action name="ajaxcall" class="com.logic.action.CustomerAction" method="ajaxcall">
       <result name="success" >/pages/customer/addCustomer.jsp</result> 
   </action>

I think the error is in the action class-response statement and in struts.xml. Can any one please help me to fix this issue. Thanks in Advance.

我认为错误出在 action class-response 语句和 struts.xml 中。任何人都可以帮我解决这个问题。提前致谢。

回答by Umesh Awasthi

I believe this simple code should work for Ajax calling.The example below is using stream result but you can use even JSON,XML or any other format you want as return. As a server-side struts2 did not take in to account if request is coming from script/ajax or any other way

我相信这个简单的代码应该适用于 Ajax 调用。下面的示例使用流结果,但您甚至可以使用 JSON、XML 或任何其他您想要的格式作为返回。作为服务器端 struts2 没有考虑到请求是来自脚本/ajax 还是任何其他方式

Action

行动

public class TextResult extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }

    public String execute() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }
}

Struts.xml file

Struts.xml 文件

struts.xml

struts.xml

<action name="text-result" class="actions.TextResult">
    <result type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStream</param>
    </result>
</action>

you can use above setup with your JS. On successful calling Action will return "Hello World! This is a text string response from a Struts 2 Action."string

您可以将上述设置与您的 JS 一起使用。成功调用 Action 将返回“Hello World!这是来自 Struts 2 Action 的文本字符串响应”。细绳

Update

更新

Here is a complete working code as an Ajax call

这是一个完整的工作代码作为 Ajax 调用

JSP Code

JSP代码

<head>
<script type="text/javascript">
            var xmlHttp;
            function ajaxEditFunctionCall(){

                var URL = "welcomeAjax.action?stateName=State1";
                try{
                    xmlHttp=new XMLHttpRequest();
                }catch (e){
                    try{
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                    }catch (e){
                        try{
                            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e){
                            alert("Your browser does not support AJAX!");
                            return false;
                        }
                    }
                }
                //alert(1);
                xmlHttp.onreadystatechange = showMessage;
                //alert(2);

                xmlHttp.open("GET", URL, true);

                //alert(3);
                xmlHttp.send(null);
            }

            function showMessage() {
                //alert("Inside Show Message1");
                //alert(xmlHttp.readyState);
                if(xmlHttp.readyState==4)
                {
                    alert("Inside Show Message2&ReadyState4");
                    alert(xmlHttp.responseText);
                }
            }  
        </script>
</head>
<body>
<s:form id="form">
<input type="button" onclick="ajaxEditFunctionCall()"/>
</s:form>
<body>

Here is the code from Action class

这是来自 Action 类的代码

Action

行动

private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }

    public String ajax() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }

Finally we need to define the relation in struts.xml file

最后我们需要在 struts.xml 文件中定义关系

struts.xml

struts.xml

<action name="welcomeAjax" class="com.demo.WelcomeAction" method="ajax">
            <result type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
 </action>

the above code is working perfectly fine and hope will help you.

上面的代码工作得很好,希望能帮到你。

回答by James Jithin

Here, the correction needs to be done to the JavaScript function. When you say var xmlHttp, it has a scope inside the function ajaxEditFunctionCalland not for the showMessage. Also, xmlhttpin showMessage()is not same as xmlHttpobject in ajaxEditFunctionCall. So, keep the var xmlHttpdeclaration global and make the corrections. Here is the working code:

这里需要对JavaScript函数进行修正。当你说的时候var xmlHttp,它在函数内部有一个作用域,ajaxEditFunctionCall而不是为showMessage. 此外,xmlhttpinshowMessage()xmlHttp对象 in 不同ajaxEditFunctionCall。因此,保持var xmlHttp声明全局并进行更正。这是工作代码:

<script type="text/javascript">
            var xmlHttp;
            function ajaxEditFunctionCall(){

                var URL = "ajaxcall.action?stateName=State1";
                try{
                    xmlHttp=new XMLHttpRequest();
                }catch (e){
                    try{
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                    }catch (e){
                        try{
                            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e){
                            alert("Your browser does not support AJAX!");
                            return false;
                        }
                    }
                }
                //alert(1);
                xmlHttp.onreadystatechange = showMessage;
                //alert(2);

                xmlHttp.open("GET", URL, true);

                //alert(3);
                xmlHttp.send(null);
            }

            function showMessage() {
                //alert("Inside Show Message1");
                //alert(xmlHttp.readyState);
                if(xmlHttp.readyState==4)
                {
                    alert("Inside Show Message2&ReadyState4");
                    alert(xmlHttp.responseText);
                }
            }  
        </script>

The Java code is:

Java代码是:

public class CustomerAction extends ActionSupport implements ServletResponseAware {

    HttpServletResponse response;

    public String ajaxcall() {

        System.out.println("Inside AjaxCall");
        String errorXml = "This is a Sample to Check";

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");
        try {
            response.getWriter().write(errorXml);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return null;
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
}

The struts.xml is:

struts.xml 是:

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="default" extends="struts-default">
        <action name="ajaxcall" class="com.logic.action.CustomerAction" method="ajaxcall">
            <result name="success" >/pages/customer/addCustomer.jsp</result>
        </action>
    </package>
</struts>

回答by amit kate

above example is perfectly working

上面的例子是完美的工作

to convert into json object use

转换成json对象使用

jsonobj=jQuery.parseJSON(req.responseText);