The following uses Struts2+jquery+json to simulate a case. When the Submit button is clicked, the input data is submitted to the background, and the data is displayed in the client from the background.
The effect is as follows:
Next to the Struts2+jquery+json integration steps:
1, create a new Web project, import Struts2+jquery+json required jar, such as
Directory structure diagram
2. Create entity class User
Package Com.ljq.bean;import java.io.Serializable; @SuppressWarnings ("Serial") Public classUser implements Serializable {Private intID; PrivateString username; PrivateString pwd; PublicUser () {} PublicUser (intID, string username, string pwd) {super (); This. ID =ID; This. Username =username; This. PWD =pwd; } Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString getpwd () {returnpwd; } Public voidsetpwd (String pwd) { This. PWD =pwd; }}
3. New Action Jsonaction
Package Com.ljq.action;import Net.sf.json.jsonobject;import com.ljq.bean.user;import Com.opensymphony.xwork2.ActionSupport; @SuppressWarnings ("Serial") Public classJsonaction extends actionsupport{Privateuser User; //returns the result to the client PrivateString result; @Override PublicString Execute () throws Exception {//JSON processing of entity objects that will be returnedJsonobject json=jsonobject.fromobject (user); //output format such as: {"id": 1, "username": "Zhangsan", "pwd": "123"}System. out. println (JSON); Result=json.tostring (); returnSUCCESS; } PublicUser GetUser () {returnuser; } Public voidsetUser (user user) { This. user =user; } PublicString GetResult () {returnresult; } Public voidSetresult (String result) { This. result =result; }}
4. Establish Struts.xml file
<?xml version="1.0"encoding="UTF-8"? ><!DOCTYPE Struts public"-//apache software foundation//dtd Struts Configuration 2.0//en" "HTTP://STRUTS.APACHE.ORG/DTDS/STRUTS-2.0.DTD"><struts> <!--This property specifies the request suffix that needs to be Struts2 processed, and the default value of the property is action, which is all matches *the. Action request is handled by STRUTS2. If the user needs to specify multiple request suffixes, the multiple suffixes are separated by commas (,). -<constant Name="struts.action.extension"Value=" Do"/> <!--Set whether the browser caches static content, the default value is True (used in a production environment), and the development phase is best off--<constant name="Struts.serve.static.browserCache"Value="false"/> <!--When the configuration file for struts is modified, the system automatically reloads the file, the default value is False (used in production), and the development phase is best opened--<constant name="Struts.configuration.xml.reload"Value="true"/> <!--development mode, so you can print out more detailed error messages--<constant name="Struts.devmode"Value="true"/> <!--default View theme-<!--<constant Name="Struts.ui.theme"Value=" Simple"/>-<!--<constant Name="struts.objectfactory"Value="Spring"/>--<package name="Test"extends="Json-default"> <action name="jsonaction" class="com.ljq.action.JsonAction"> <result type="JSON"> <!--here the value of Reslut is returned to the client, and the value of root corresponds to the property of the value to be returned result note: Root is a fixed notation, otherwise the value of result will not be returned to the client-<param Name="Root">result</param> </result> </action> </package></struts>
5. Writing index.jsp files
<%@ page language="Java"import="java.util.*"pageencoding="UTF-8"%><% @taglib uri="/struts-tags"prefix="s"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () +"://"+ request.getservername () +":"+Request.getserverport ()+ Path +"/";%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en">Basehref="<%=basePath%>"> <title>my JSP'index.jsp'Starting page</title> <meta http-equiv="pragma"Content="No-cache"> <meta http-equiv="Cache-control"Content="No-cache"> <meta http-equiv="Expires"Content="0"> <meta http-equiv="keywords"Content="Keyword1,keyword2,keyword3"> <meta http-equiv="Description"Content="This is my page"> <script type="Text/javascript"Src="<%=request.getcontextpath ()%>/js/jquery-1.3.1.js"></script> <script type="Text/javascript"Src="<%=request.getcontextpath ()%>/js/index.js"></script> <!--<s:head theme="Ajax"/> This sentence seems to have no effect oh-<!--<s:head Theme="Ajax"/>--> <!--add <s:head theme= to the JSP page"Ajax"/>will report the following exception: Java.io.FileNotFoundException:Template/template/ajax/HEAD.FTL not found. Workaround: In Struts2-core-2.1.8. jar/Add Ajax folder under the template directory, the Ajax folder directory is struts2-core-2.1.8. jar/template/Archive. Note: The Ajax folder should contain HEAD.FTL, otherwise it will throw an exception. HEAD.FTL please search in the template directory and put it in the Ajax folder.-"result"></div> <s:form name="UserForm"action="/jsonaction.do"Method="Post">Number:<input name="user.id"/><br/>User name:<input name="User.username"/><br/>Password:<input name="user.pwd"/><br/><br/> <input id="btn"Type="Button"Value="Submit"/> </s:form> </body>6. Establish document Index.js
$ (document). Ready (function () {//When you click the Submit button, the data is fetched from the server and then displayed on the client$("#btn"). Click (function () {//serialize the value of the form var params=$("input"). Serialize (); $.ajax ({URL:"jsonaction.do", //How data is sentType"Post", //Accept Data FormatDataType:"JSON", //the data to be passedData:params, //callback function that accepts the value returned to the client by the server side, that is, the result valuesuccess:show}); });}); function Show (result) {//tests whether result is returned to the client from the server side//alert (result); //parsing JSON objects varJSON = eval ("("+result+")"); varobj ="Number:"+json.id+"User name:"+json.username+"Password:"+json.pwd; $("#result"). html (obj);}Struts2+jquery+json Integration