Use jQuery to implement AJAX applications in the struts2 framework

Source: Internet
Author: User

As we all know, in the web era, if any web framework is not tied to AJAX, I am embarrassed to say how NB my framework is. Of course, struts is no exception, from struts1 to the present, struts2 also supports AJAX. There are many data formats (such as xml, html, plain text, and json) during AJAX transmission. Here we demonstrate the transmission in json format. Some may read related technical blogs, and some may use the struts2 plug-in (e.g ., JSON plugin, jQuery plugin). This method is theoretically more efficient for development, but it is a bit difficult for developers who have never touched AJAX, the author is in struts2 basic jar, through the json-lib.jar as a bridge between java objects and json objects, front-end web pages with jQuery to achieve AJAX receiving and receiving. The project built by the author is created through Maven. The dependencies of the project are as follows: pom. xml: Copy Code <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> com. hzc </groupId> <artifactId> struts_2400_AJAX_jQuery </artifactId> <packaging> war </packaging> <version> 0.0.1-SN APSHOT </version> <name> struts_2400_AJAX_jQuery Maven Webapp </name> <url> http://maven.apache.org </url> <dependencies> <dependency> <groupId> junit </groupId> <artifactId> junit </artifactId> <version> 4.4 </version> <scope> test </scope> </dependency> <groupId> org. apache. struts </groupId> <artifactId> struts2-core </artifactId> <version> 2.3.16 </version> </dependency> <groupId> net. sf. Json-lib </groupId> <artifactId> json-lib </artifactId> <version> 2.4 </version> <classifier> jdk15 </classifier> <! -- To obtain the jar package of json-lib, jdk must be specified, yes. jdk version --> </dependency> </dependencies> <build> <finalName> struts_2400_AJAX_jQuery </finalName> </build> </project> let's take a look, think about the client for xxx. action to send a request, you need to transmit a java object to the client, struts2 according to struts. the xml configuration helps us intercept this request and execute the execute () method. In general, we return a page, but to achieve AJAX, we cannot jump to the page, so I/O is used for output. Struts. xml: copy the Code <? 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> <! -- Add packages here --> <constant name = "struts. devMode" value = "true"/> <! -- This label sets struts2 as the debug mode, update the changed code at any time --> <package name = "registration" namespace = "/" extends = "struts-default"> <action name = "login" class = "com. hzc. action. userAction "> <result type =" stream "> <param name =" contentType "> text/html </param> <param name =" inputName "> inputStream </param> </result> </action> </package> </struts> copy the code and specify stream as the result type, and configure the stream parameters. Note that <param name = "inputName"> inputStream </param> InputStream is a member variable in action. The json data output is included in this object. UserAction. java: copy the code package com. hzc. action; import java. io. byteArrayInputStream; import java. io. inputStream; import net. sf. json. JSONObject; import com. hzc. model. user; import com. opensymphony. xwork2.ActionSupport; public class UserAction extends ActionSupport {private String jsonStr; private User user; private InputStream inputStream; public String getJsonStr () {return jsonStr;} public void setJs OnStr (String jsonStr) {this. jsonStr = jsonStr;} public User getUser () {return user;} public void setUser (User user User) {this. user = user;} public InputStream getInputStream () {return inputStream;} public void setInputStream (InputStream inputStream) {this. inputStream = inputStream;} @ Override public String execute () throws Exception {// System. out. println (user. getId (); JSONObject myjJsonObj Ect = new JSONObject (). fromObject (jsonStr); System. out. println (JSONObject. toBean (myjJsonObject, User. class); User user = new User (); user. setName ("hzc"); user. setAge (22); JSONObject jsonObject = new JSONObject (). fromObject (user); inputStream = new ByteArrayInputStream (jsonObject. toString (). getBytes ("UTF-8"); return SUCCESS;} copy the code to ignore the jsonStr variable! The user object is converted to a json string (), JSONObject jsonObject = new JSONObject (). fromObject (user); after calling the toString () method, you can write a json string to the created inputStream. Of course, do not forget return SUCCESS; json output string: {"age": 22, "id": 0, "name": "hzc"} at the front end, the webpage uses the $. the ajax () method is used to send json to the server. Then, the server performs the relevant business logic based on the data sent from the front-end, and finally outputs the result as a json string. In the ajax function, success is the method to be executed after the callback is successful. Here we simply parse the json sent from the server and fill it in the text box! Copy code $ (document ). ready (function () {$ ("# sendButton "). click (function () {var jsonAttr = $ ("# userName "). attr ('name'); var jsonData =$ ("# userId "). val (); $. ajax ({type: "post", url: "http: // 192.168.80.1: 8080/struts_2400_AJAX_jQuery/login. action ", data:" jsonStr = {'id': "+ jsonData +"} ", success: function (msg) {var jsonObject = $. parseJSON (msg); $ ("# userName "). attr ('value', jsonObject [jsonAttr]);}, e Rror: function (e) {alert (e) ;}}) ;}); copy the Code <body> id: <input type = "text" id = "userId"/> <button id = "sendButton"> ajax </button> <br/> name: <input type = "text" name = "name" id = "userName"/> </body> the last thing I want to talk about here is because I am also a beginner, just think of passing the json string to the server (that is, struts2) by adding a parameter after the url. jsonStr is the member variable in the corresponding action. If you have a better way to write this blog, leave your thoughts behind.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.