AJAX request processing Struts2

 

Struts2 integration of AJAX in two ways:

  • Use type = "stream" type <result>
  • Using JSON plugin

 

 


 

 

Use type = "stream" type <result> Get text

front end

  <body>
  <form>
    学号:<input type="text" id="no"><br />
    姓名:<input type="text" id="name"><br />
    <button type="button" id="btn">查询成绩</button>
  </form>
  <p id="score"></p>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",   
        type:"get",   
        data:{"no":$("#no").val(),"name":$("#name").val()},
        dataType:"text",
        error:function () {
          console.log("ajax请求失败!")
        },
        success:function (data) {
          $("#score").text(data);
        }
      })
    });
  </script>
  </body>

and in struts.xml url to the action name, namespace corresponding to the package.

 

 

action

public class HandlerAction extends ActionSupport {
    private int no;
    private String name;
    private InputStream inputStream;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    publicThe getInputStream the InputStream () {
         return inputStream; 
    } 

    public  void setInputStream (the InputStream inputStream) {
         the this .inputStream = inputStream; 
    } 

    @Override 
    public String Execute () throws Exception {
         // here default connection database query out 
        String result = name + "students, your total score is: 680" ;
         // set the data to be returned. We pass the browser data contains Chinese, need to set utf-8 encoding, to resolve the Chinese distortion 
        inputStream = new new A ByteArrayInputStream (result.getBytes ( " utf-8 " ));
         return SUCCESS; 
    } 
}

Sent back to the front end of two fields: no, name

action need to set two member variables of the same name, and to provide a corresponding getter, setter method, in order to receive data transmitted to the front end.

InputStream need a member variable of type and provide corresponding getter, setter, returning data to the browser.

Method (Execute) requires a processing request, the data set returned to the browser.

 

 

struts.xml

<Struts> 
    < Package name = "Action" namespace = "/" the extends = "Struts-default"> 
        <Action name = "HandlerAction" class = "action.HandlerAction">
             <name = Result "Success" type = "Stream" > 
                <! - the return data type is provided to the browser -> 
                <param name = "contentType"> text / HTML </ param> 
                <! - the specified method takes an InputStream is, getInputStream (), convention: remove get, use later camel wording -> 
                <param name = "the inputName"> inputStream </ param> 
            </ Result> 
        </ Action> 
    </package>
</struts>

 

 

Process Analysis

  • Ajax request to send back the front end, passing no, name2 field
  • Create action JVM instance, call no, name corresponding setter method to assign a value to pass over the tip member variables (will be automatically converted to the target type), to complete the action of initialization
  • JVM calls the action processing business method execute, set to return to the browser data
  • The JVM struts.xml the <result> method specified (getInputStream), obtaining InputSteam, the inside of the data to the browser.

 

 


 

 

 

Use type = "stream" type <result> Get json

front end

 <body>
  <form>
    学号:<input type="text" id="no"><br />
    <button type="button" id="btn">查询学生信息</button>
  </form>
  <div id="show"></div>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",
        type:"post",
        data:{"no":$("#no").val()},
        dataType:"json",
        },)"Ajax request failed!"
          the console.log (
        error: function () {
        success:function (data) {
          $("#show").append("姓名:" + data.name+",");
          $("#show").append("年龄:" + data.age+",");
          $("#show").append("成绩:" + data.score+"。");
        }
      })
    });
  </script>
  </body>

 

 

action

public class HandlerAction extends ActionSupport {
    private int no;
    private InputStream inputStream;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override 
    public String Execute () throws Exception {
         // here default connection database query to obtain information Student 
        Student Student = new new Student (. 1, "Joe Smith", 20 is, 100 );
        String jsonStr = JSON.toJSONString (Student);

         // set the data to be returned 
        inputStream = new new a ByteArrayInputStream (jsonStr.getBytes ( "UTF-. 8" ));
         return SUCCESS; 
    } 
}

Ali used the fastjson.jar, the need to introduce yourself to download.

 

 

struts.xml

Configuration Ibid

 

 


 

 

 

AJAX with JSON plug-in implementation

front end

<body>
  <form>
    学号:<input type="text" id="no"><br />
    <button type="button" id="btn">查询学生信息</button>
  </form>
  <div id="show"></div>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",
        type:"post",
        data:{"no":$("#no").val()},
        dataType:"json",
        },)"Ajax request failed!"
          the console.log (
        error: function () {
        success:function (data) {
          $("#show").append("姓名:" + data.student.name+",");
          $("#show").append("年龄:" + data.student.age+",");
          $("#show").append("成绩:" + data.student.score+"。");
        }
      })
    });
  </script>
  </body>

 

 

action

public class HandlerAction extends ActionSupport {
    private int no;
    private Student student;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public String execute() throws Exception {
         // here default connection database query to obtain the student information 
        Student = new new Student (. 1, "Joe Smith", 20 is, 100 );
         return SUCCESS; 
    } 
}

Need to set the member variable of the same name, and provide getter, setter methods to receive data from the front-end.

In this way by the action plug-in JSON objects serialized to JSON format string, passed to the browser. The browser can directly access the action of all members of the variables (in essence, call the corresponding getter method).

We just need to ajax request data package for the action of the member variables and provide a corresponding getter, setter methods. Required data to the request before the scheduling assignment method (Execute) return statement.

success:function (data) {
          $("#show").append("姓名:" + data.student.name+",");
          $("#show").append("年龄:" + data.student.age+",");
          $("#show").append("成绩:" + data.student.score+"。");
}

Browser data received data itself is action example, through the Access member variables.

 

 

struts.xml

<Struts> 
    < Package name = "Example" namespace = "/" the extends = "JSON-default" > 
        <Action name = "HandlerAction" class = "action.HandlerAction"> 
            <-! type = "JSON" of the result, the default name attribute can, of course, also write on line -> 
            <the Result of the type = "json" > 
                <param name = "noCache"> to true </ param> 
                <-! is set to return to the browser the type of data -> 
                <param name = "contentType"> text / HTML </ param> 
            </ Result> 
        </ Action> 
    </package>
</struts>

 json-default configuration package inherits the struts-default package, so do not inherit the struts-default.

 

 

Explanation

Need to manually add JSON plug-struts2-json-plugin.jar.

The above package has a compression jar containing all the struts, including the struts2-json-plugin.jar.

The following archive only eight struts core jar package.

Guess you like

Origin www.cnblogs.com/chy18883701161/p/12112589.html