温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Struts2如何处理AJAX请求

发布时间:2022-03-19 16:24:55 来源:亿速云 阅读:224 作者:iii 栏目:web开发

本文小编为大家详细介绍“Struts2如何处理AJAX请求”,内容详细,步骤清晰,细节处理妥当,希望这篇“Struts2如何处理AJAX请求”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

Struts2 处理AJAX请求

Struts2整合AJAX有2种方式:

  • 使用type="stream"类型的<result>

  • 使用JSON插件

使用type="stream"类型的<result>  获取text

前端
  <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>

url要和struts.xml中action的name、包的namespace对应。

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;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

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

    @Override
    public String execute() throws Exception {
        //此处缺省连接数据库查询总分
        String result = name + "同学,你的总分是:680";
        //设置要返回的数据。我们传给浏览器的数据含有中文,需要设置utf-8编码,来解决中文乱码
        inputStream=new ByteArrayInputStream(result.getBytes("utf-8"));
        return SUCCESS;
    }
}

前端向后台发送了2个字段:no、name

action需要设置2个同名的成员变量,并提供对应的getter、setter方法,才能接收到前端传来的数据。

需要一个InputStream类型的成员变量,并提供对应的getter、setter,用于向浏览器返回数据。

需要一个处理请求的方法(execute),设置返回给浏览器的数据。

struts.xml

<struts>
    <package name="action" namespace="/" extends="struts-default">
        <action name="HandlerAction" class="action.HandlerAction">
            <result name="success" type="stream">
                <!-- 设置返回给浏览器的数据类型 -->
                <param name="contentType">text/html</param>
                <!--指定获取InputStream的方法,getInputStream(),约定:去掉get,后面部分使用camel写法 -->
                <param name="inputName">inputStream</param>
            </result>
        </action>
    </package>
</struts>
流程分析
  • 前端向后台发送ajax请求,传递no、name2个字段

  • JVM创建action实例,调用no、name对应的setter方法把前端传过来的值赋给成员变量(会自动转换为目标类型),完成action的初始化

  • JVM调用action处理业务的方法execute,设置向浏览器返回的数据

  • JVM根据struts.xml中<result>指定的方法(getInputStream),获取InputSteam,将里面的数据传给浏览器。

使用type="stream"类型的<result>  获取json

前端
 <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",
        error:function () {
          console.log("ajax请求失败!")
        },
        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 {
        //此处缺省连接数据库查询得到学生信息
        Student student = new Student(1, "张三", 20, 100);
        String jsonStr = JSON.toJSONString(student);

        //设置要返回的数据
        inputStream=new ByteArrayInputStream(jsonStr.getBytes("utf-8"));
        return SUCCESS;
    }
}

使用了阿里的fastjson.jar,需要自己下载引入。

struts.xml

配置同上

使用JSON插件实现AJAX

前端
<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",
        error:function () {
          console.log("ajax请求失败!")
        },
        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 {
        //此处缺省连接数据库查询得到学生信息
        student = new Student(1, "张三", 20, 100);
        return SUCCESS;
    }
}

需要设置同名的成员变量,并提供getter、setter方法,来接收前端传来的数据。

此种方式是由JSON插件把action对象序列化为一个JSON格式的字符串,传给浏览器。浏览器可以直接访问action的所有成员变量(实质是调用对应的getter方法)。

我们只需要把ajax要请求的数据封装为action的成员变量,并提供对应的getter、setter方法。需要在主调方法(execute)的return语句之前对请求的数据赋值。

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

浏览器接受到的数据data本身就是action实例,可通过.访问成员变量。

struts.xml
<struts>
    <package name="example" namespace="/" extends="json-default">
        <action name="HandlerAction" class="action.HandlerAction">
            <!--type="json"的result,可以缺省name属性,当然写上也行-->
            <result type="json">
                <param name="noCache">true</param>
                <!-- 设置返回给浏览器的数据类型 -->
                <param name="contentType">text/html</param>
            </result>
        </action>
    </package>
</struts>
说明

需要手动添加JSON插件 struts2-json-plugin.jar 。

Struts2如何处理AJAX请求

上面的压缩包含有struts的所有jar包,其中就包括了struts2-json-plugin.jar。

下面的压缩包只有struts核心的8个jar包。

读到这里,这篇“Struts2如何处理AJAX请求”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI