search
HomeWeb Front-endJS TutorialStruts2 and Ajax data interaction (graphic tutorial)

Struts2 and Ajax data interaction (graphic tutorial)

May 21, 2018 pm 04:24 PM
ajaxstruts2Graphics and text

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 id="异步登录">异步登录</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 id="异步登录">异步登录</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 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>

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");

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!

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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.