Home  >  Article  >  Web Front-end  >  Detailed explanation of realizing Struts2 and Ajax data interaction

Detailed explanation of realizing Struts2 and Ajax data interaction

php中世界最好的语言
php中世界最好的语言Original
2018-03-30 15:25:191008browse

This time I will bring you a detailed explanation of the data interaction between Struts2 and Ajax, and what are the precautions for realizing the data interaction between Struts2 and Ajax. The following is a practical case, let's take a look.

Preface

Let’s start with the trend of Web 2.0 and the brilliance of Ajax. The Struts2 framework itself integrates native support for Ajax. (Struts 2.1.7+, previous versions can be implemented through plug-ins), the integration of the framework only makes the creation of JSON extremely simple, and can be easily integrated into the Struts2 framework. Of course, this is only when we need JSON. Looks radiant.

ajax requests are often used in projects. Today I will summarize what I usually know about the data transfer interaction between the front page and the background action when using ajax to request an action in Struts2.

Here I mainly record several methods that I have mastered. You can choose according to your daily project needs.

1. Use the stream type result

This type can directly allow the action in Struts2 to generate a text response to the client browser.

Example:

jsp page:

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>ajax提交登录信息</title>
 <%--导入js插件--%>
 <script src="${PageContext.request.contextPath}/demo/js/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>
<body>
<h3>异步登录</h3>
<s:form id="loginForm" method="POST">
 <s:textfield name="username"/>
 <s:textfield name="psw"/>
 <input id="loginBtn" type="button" value="提交">
</s:form>
<p id="show" style="display:none;"></p>
</body>
<script type="text/javascript">
 $("#loginBtn").click(function(){
 $("#show").hide();
 //发送请求login 以各表单里歌空间作为请求参数
 $.get("login",$("#loginForm").serializeArray(),
  function(data,statusText){
  $("#show").height(80)
   .width(240)
   .css("border","1px solid black")
   .css("border-radius","15px")
   .css("backgroud-color","#efef99")
   .css("color","#ff0000")
   .css("padding","20px")
   .empty();
  $("#show").append("登录结果:"+data+"<br/>");
  $("#show").show(600);
 },"html");//指定服务器响应为html
 });
</script>
</html>

Processing logic action:

/**
 * Description:eleven.action
 * Author: Eleven
 * Date: 2018/1/26 18:09
 */
public class LoginAction extends ActionSupport{
 private String username;
 private String psw;
 //输出结果的二进制流
 private InputStream inputStream;
 public String login() throws Exception{
 if(username.equals("tom")&& psw.equals("123")){
  inputStream = new ByteArrayInputStream("恭喜您,登录成功".getBytes("UTF-8"));
 }else{
  inputStream = new ByteArrayInputStream("对不起,登录失败".getBytes("UTF-8"));
 }
 return SUCCESS;
 }
 //提供get方法
 public InputStream getInputStream() {
 return inputStream;
 }
 public String getUsername() {
 return username;
 }
 public void setUsername(String username) {
 this.username = username;
 }
 public String getPsw() {
 return psw;
 }
 public void setPsw(String psw) {
 this.psw = psw;
 }
}

In addition to the user receiving the page delivery, the action In addition to the name and password, there is also a member variable of the InputStream type, and a corresponding get method is provided for it. The binary stream returned in the get method will be output directly to the client browser.

struts.xml configuration:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="true" />
 <package name="default" namespace="/" extends="struts-default">
 <action name="login" class="eleven.action.LoginAction" method="login">
  <result type="stream">
  <!--指定stream流生成响应的数据类型-->
  <param name="contentType">text/html</param>
  <!--指定action中由哪个方法去输出InputStream类型的变量-->
  <param name="inputName">inputStream</param>
  </result>
 </action>
 </package>
</struts>

Browse the page in the browser, enter the relevant information, and then submit. You can see that the background action directly returns the message data to the page, while the page There is no need to refresh, but it is displayed directly locally. This is using ajax to send requests asynchronously. Note that this method requires configuring a stream of type stream in the struts.xml file, setting the inputName attribute, and providing the get method corresponding to InputStream in the action.

Run screenshot:

2. Use json type result

Yes A jar package struts2-json-plugin-2.3.16.3.jar can add a JSON plug-in for Struts2. That is, when the result type in the action is set to json, the action can also be called asynchronously in the client js and returned in the action. The data can be directly serialized into a json format string by the JSON plug-in, and the string is returned to the client browser.

Example:

jsp page:

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>ajax提交登录信息</title>
 <%--导入js插件--%>
 <script src="${PageContext.request.contextPath}/demo/js/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>
<body>
<h3>异步登录</h3>
<s:form id="loginForm" method="POST">
 <s:textfield name="username"/>
 <s:textfield name="psw"/>
 <input id="loginBtn" type="button" value="提交">
</s:form>
<p id="show" style="display:none;"></p>
</body>
<script type="text/javascript">
 $("#loginBtn").click(function(){
 $("#show").hide();
 //发送请求login 以各表单里歌空间作为请求参数
 $.get("login",$("#loginForm").serializeArray(),
  function(data,statusText){
  //此时的data中包含username,psw,age
  $("#show").height(80)
   .width(300)
   .css("border","1px solid black")
   .css("border-radius","15px")
   .css("backgroud-color","#efef99")
   .css("color","#ff0000")
   .css("padding","20px")
   .empty();  
  alert(data);
  $("#show").append(data+"<br/>");
  $("#show").show(600);
 },"html");
 });
</script>
</html>

action code:

public class LoginAction extends ActionSupport{
 private String username;
 private String psw;
 private int age;
 public String login() throws Exception{
  age = 18;
  return SUCCESS;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPsw() {
  return psw;
 }
 public void setPsw(String psw) {
  this.psw = psw;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

configuration in struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="true" />
 <package name="default" namespace="/" extends="struts-default,json-default">
  <action name="login" class="eleven.action.LoginAction" method="login">
   <result type="json">
    <param name="noCache">true</param>
    <param name="contentType">text/html</param>
   </result>
  </action>
 </package>
</struts>

Browse the page in the browser, enter relevant information, and then submit. You can see that the background action directly returns the message data to the page. At the same time, the page does not need to be refreshed, but is directly displayed locally. This It uses ajax to send requests asynchronously. Note that this method requires configuring the package to inherit json-default in the struts. Of course, the premise is that struts2-json-plugin-2.3.16.3.jar is added, otherwise struts2 will not automatically convert the data into json format data.

Screenshot of the effect:

So we can summarize the steps for the result type to be json:

1. Import the jar package: struts2- json-plugin-2.3.7.jar 

 2. Configure the result set view returned by struts and set type=json

 3. Set the package where the corresponding action is located to inherit from json-default

4. Provide the get method for the data to be returned

5. Set the format of the returned data in struts.xml

For step 5, set the format of the returned data according to your own project If you need, go to the specific settings. This is just a simple example, and no complex data is taken. If a List collection is returned, the data format can be set as follows:

<result name="test" type="json">
  <!-- 设置数据的来源从某个数据得到 -->
   <!-- 过滤数据从gtmList集合中得到,且只获取集合中对象的name,跟uuid属性 -->      <param name="root">gtmList</param>
  <param name="includeProperties">
    \[\d+\]\.name,
    \[\d+\]\.uuid
  </param> 
</result>

In addition to the above method, there are also There is the following way

<result name="ajaxGetBySm" type="json">
   <!-- 一般使用这种方式 先用来源过滤action默认从整个action中获取所有的(前提是此action中没有getAction()方法)
    但是为了方便 一般不写root:action这个
    然后再用包含设置进行过滤设置
   -->    
   <param name="root">action</param>
   <param name="includeProperties">
     gtmList\[\d+\]\.name,
     gtmList\[\d+\]\.uuid
   </param>
 </result>

上面两种方式都是设置数据从gtmList集合中获取且,只获取对象的属性为name与uuid的。这里只做简单的举例,具体可自己下去深入研究。

附上json类型的Result允许指定的常用参数:

另外,除了以上两种是struts2支持的ajax外,其实如果单纯的只是可以让服务器端可以跟客户端浏览器进行数据交互,可以使用response.getWrite()这种方式。

PrintWriter printWriter =response.getWriter();
printWriter.print("success");

选择哪种方式?

对于我,如果只是对增删改功能是否成功的一个flag判断的数据,则可优先选择response.getWriter().print("xxx")与设置result类型为stream的方式,但是如果是需要返回大量对象数据,在页面接收然后进行数据展示,例如页面通过ajax请求,需要后台action返回一个list集合,则就要选择配置result类型为json的方式了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

使用Ajax和forms实现注册用户所需功能

ajax实现动态饼图和柱形图的图文详解

The above is the detailed content of Detailed explanation of realizing Struts2 and Ajax data interaction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn