STRUTS2 + ajax + JSON combined use, examples explained

Source: Internet
Author: User

Struts2 with response how to return the JSON value to the page JavaScript parsing, here is a struts2 and JSON integration after the use of the package.

1. Preparatory work

①ajax using Jquery:jquery-1.4.2.min.js

②struts2 and JSON dependency package: Struts2-json-plugin-2.2.3.jar

PS: Version can be controlled by itself! ~

2. Process

① Introducing JSON Dependency packages

② writing the Action class

③ Configuration Struts.xml

④ writing a page

⑤ Test

3. Example

①action class, jsonaction Note package name

 Packagecom.zxt.action;ImportCom.opensymphony.xwork2.ActionSupport;/*** * @Title: jsonaction.java* @Package com.zxt.action* @Description: Struts2 + ajax + JSON use case *@authorZXT * @date 2011-12-6 a.m. 10:38:51*@versionV1.0*/ Public classJsonactionextendsActionsupport {/**  *  */ Private Static Final LongSerialversionuid = 7443363719737618408L; /*** Name*/ PrivateString name;/*** Height*/ PrivateString inch;/*** Ajax return results, but also other types, here is the case of string type*/ PrivateString result; @Override PublicString Execute ()throwsException {//TODO auto-generated Method Stub  if("Zhang San". Equals (name)) {Result= "Authentication passed, height is" +inch; } Elseresult= "Not Zhang San!" "; returnSUCCESS;}  PublicString GetName () {returnname;}  Public voidsetName (String name) { This. Name =name;}  PublicString Getinch () {returninch;}  Public voidSetinch (String inch) { This. inch =inch;} /*** * @Title: GetResult * @Description: JSON fetch result *@param @return    * @returnString *@throws  */  PublicString GetResult () {returnresult;} }

②struts configuration. Struts.xml

Create a new package that introduces Json-default

< Packagename= "Ajax"extends= "Json-default">    <Actionname= "Jsonajax"class= "Com.zxt.action.JsonAction">       <!--set the return type to JSON -      <resulttype= "JSON"></result>    </Action>  </ Package>

③ page Ajax notation, json.jsp

<%@ Pagelanguage= "Java"ContentType= "text/html; charset=utf-8"pageencoding= "UTF-8"%><%stringPath= Request.getcontextpath ();String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Basehref= "<%=basePath%>"><Metahttp-equiv= "Content-type"content= "text/html; charset=iso-8859-1"><title>Test</title><Scripttype= "Text/javascript"src= "Include/js/jquery-1.4.2.min.js"></Script><Scripttype= "Text/javascript">$ (function () {$ ("#tj"). Click (function () {///submit parameter, name and inch are the corresponding receive variables in the struts action var params = {        Name: $ ("#xm"). Val (), Inch: $ ("#sg"). Val ()}; $.ajax ({type: "POST", url: "Jsonajax.action", Data:params, DataType: "Text",//ajax return value set to text (JSON format is also available for it to return, can be hit  Printed results, can also be set to JSON) Success:function (JSON) {var obj = $.parsejson (JSON);  Use this method to parse the JSON var state_value = Obj.result;    Result is the alert (state_value) corresponding to the Get method of the result variable defined in the action;     }, Error:function (JSON) {alert ("json=" + JSON);    return false;     }    });   }); });</Script></Head><Body>  <span>Name:</span><inputID= "XM"type= "text">  <BR/>  <span>Height:</span><inputID= "SG"type= "text">  <BR/>  <inputtype= "button"value= "Submit"ID= "TJ"></Body></HTML>

④ start the site, test it! ~

Press this to finish, everything OK. Prepare for the test and see how powerful it works! ~o (∩_∩) o~

This is just the simplest example (front background interaction), he can do a lot of work, play with your thoughts and talents! ~

Good luck!

Ps:

jquery Parse list When you can refer to, the following small example

var data = {"List": [{"id": 1, "Content": "Test information 1111"},{"id": 2, "Content": "Test information 2222"}]}    function(i, item) {     alert (item.id);     alert (item.content);  });

STRUTS2 + ajax + JSON combined use, examples explained

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.