Home > Web Front-end > JS Tutorial > body text

Struts2 and Ajax data interaction (graphic tutorial)

亚连
Release: 2018-05-21 16:24:37
Original
1965 people have browsed it

This article mainly introduces you to the relevant information about Struts2 and Ajax data interaction. The article introduces it in detail through sample code. It has certain reference learning value for everyone's study or work. Interested students should take a look. Just give it a try.

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 only appears when we need JSON. Ambilight.

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>
Copy after login

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;
 }
}
Copy after login

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>
Copy after login

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>
Copy after login

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;
 }
}
Copy after login

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>
Copy after login

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>
Copy after login

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

<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>
Copy after login

The above two methods are to set the data to be obtained from the gtmList collection and only obtain the attributes of the object as name and uuid. Here are only simple examples, you can go and study them in depth yourself.

Attached are the common parameters that are allowed to be specified by the json type Result:

In addition, in addition to the above two types of ajax supported by struts2, in fact, if it is simply It just allows the server to interact with the client browser by using response.getWrite().

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

Which way to choose?

For me, if it is just a flag to judge whether the addition, deletion and modification functions are successful, I can give priority to response.getWriter().print("xxx") and setting the result type to stream, but if it is necessary Return a large amount of object data, receive it on the page and then display the data. For example, if the page requests through Ajax and needs a background action to return a list collection, then you must choose to configure the result type as json.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

MUi framework ajax request WebService interface instance_AJAX related

jquery ajax implements file upload function ( Code attached)

Implement ajax drag-and-drop upload of files (code attached)

The above is the detailed content of Struts2 and Ajax data interaction (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template