Struts2 and Ajax data interaction (graphic tutorial)
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>
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 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

The principle of the Struts2 framework: 1. The interceptor parses the request path; 2. Finds the complete class name of the Action; 3. Creates the Action object; 4. Execute the Action method; 5. Returns the result; 6. View parsing. Its principle is based on the interceptor mechanism, which completely separates the business logic controller from the Servlet API, improving the reusability and maintainability of the code. By using the reflection mechanism, the Struts2 framework can flexibly create and manage Action objects to process requests and responses.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.
