Java: struts2 + jquery + Ajax call demonstration

Source: Internet
Author: User

Environment:

Operating System: Windows 7

Application Server: APACHE-Tomcat-7.0.11

Development Tool: intellij idea 11.1.1

Java version: Java (TM) se Runtime Environment (build 1.7.0 _ 03-b05)

Struts version: Struts-2.2.1.1

Jquery version: 1.7.2

MySQL version: 5.5.16 MySQL Community Server (GPL)

Mysql-connector-Java: 5.1.15


Note: In this example, the JSON data format is used. Jackson with better performance is recommended for serialization instead of JSON-lib.


Key points:

1. Import package: struts2 must be used to serialize JSON data.Struts2-json-plugin, JSON-libPackage;

2. JSON data processing: asynchronous submission of data in JSON format, the struts2-json-plugin will be JSON processing of data, so the extends of the package node in struts. xml of struts2 configuration file must be:Extends = "JSON-Default ";

For example:<Package name = "default" namespace = "/test" extends = "JSON-Default">

3.Because JSON data is returned, the result type must also be JSON;

Note: struts2 can only be introduced in the JSON-lib, struts2-json-plugin package, the type attribute of result set JSON will not report the error: <result name = "userinfo" type = "JSON"> </result>

4. For Asynchronous submission, the value of the result node of the action should be null, that is, it cannot be switched (for example, it can only be<Result name = "userinfo" type = "JSON"> </result>);

Time series:

Green indicates the client request; purple indicates that the database is returned to the client.

JSP----- (Form submission) ---->Jquery------ (Ajax asynchronous) ----->Struts2----- (Action obtains JSON data) ----->Call Service------->Others (Spring, hibernate, etc)----- (Model) ----->DB

DB ---- (model) ------> hibernate, spring ---------> service ------- struts2 (action, result) -------> jquery (Ajax) ----------> JSP


Code:

1. Entry JSP: input_user.jsp

<% -- Created by intellij idea. user: anyx date: 12-4-15 time: PM to change this template use file | Settings | file templates. -- %> <% @ page contenttype = "text/html; charset = UTF-8 "Language =" Java "%> <HTML> 

2. jquery file: myjs. js

$ (Document). Ready (function () {$ ("# MSG"). Click (function () {$. Ajax ({URL: '/test/input_user! Queryhello ', type: 'post', data: "{}", datatype: 'json', success: function (data) {$ ("# alluser "). append ("output: ID:" + data. hello) ;}});/* $. getjson ("/test/input_user! Queryhello ", function (data) {// pass. operators can be retrieved from data. in hello, get the value of hello in Action $ ("# alluser" ).html ("output:" + data. hello);}); */}); $ ("# msguserinfo "). click (function () {$. ajax ({URL: '/test/userinfo! Loaduserinfo ', type: 'post', data: "{}", datatype: 'json', success: function (data) {$ ("# alluser "). append ("<div> output: ID:" + data. userinfo. ID + ", name:" + data. userinfo. name + "</div>") ;}}) ;}) ("# msguserinfolist "). click (function () {$. ajax ({URL: '/test/userinfolist. action ', type: 'post', data: "{}", datatype: 'json', success: function (data) {/* $. each (data. userlist, function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div>") ;}); */$ (data. userlist ). each (function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div>") ;}}}) ;}); $ ("# adduser "). click (function () {// the data in the submitted form must be serialized first. jquery's serialize () method var Params = $ ("# subuserform") is used "). serialize (); $. ajax ({URL: '/test/add_user.action', type: 'post', data: Params, datatype: 'json', success: function (data) {/* $. each (data. userlist, function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div>") ;}); */$ (data. userlist ). each (function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div>") ;}}}) ;}); $ ("# users "). click (function () {$. ajax ({URL: '/test/load_alluser.action', type: 'post', data: "{}", datatype: 'json', success: function (data) {/* $. each (data. userlist, function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div>") ;}); */$ (data. userlist ). each (function (I, value) {$ ("# alluser "). append ("<div> output: ID:" + value. ID + ", name:" + value. name + "</div> ");});}});});});

3. Action class: useraction. Java

Public class useraction extends actionsupport {userservice US = new userservice (); Public String inputuser () {return "input_user";} Public String queryhello () {This. hello = "Hello World"; Return "El";} Public String loaduserinfo () {userinfo = new userinfo (); userinfo. setid (3); userinfo. setname ("Get userinfo"); Return "userinfo";} Public String loaduserinfolist () {userlist = new arraylist <userinfo> (); userinfo U1 = new userinfo (); u1.setid (1); u1.setname (" userinfo1"); userinfo U2 = new userinfo (); u2.setid (2); u2.setname (" userinfo2 "); userinfo U3 = new userinfo (); u3.setid (3); u3.setname ("Get userinfo3"); userlist. add (U1); userlist. add (U2); userlist. add (U3); Return "userinfolist";} Public String adduser () {/* userinfo = new userinfo (); userinfo. setid (7); userinfo. setname ("Zhang 7"); * // If the JSON format is submitted asynchronously, the submitted Form form must be serialized in JS first // var Params = $ ("subuserform "). serialize (); US. adduser (userinfo); userlist = us. getuser (); Return "add_success";} Public String loadalluser () {userlist = us. getuser (); Return "user";} // Private string hello; Public String gethello () {return hello;} public void sethello (string Hello) {This. hello = Hello;} public list <userinfo> getuserlist () {return userlist;} public void setuserlist (list <userinfo> userlist) {This. userlist = userlist;} public userinfo getuserinfo () {return userinfo;} public void setuserinfo (userinfo) {This. userinfo = userinfo;} private userinfo; private list <userinfo> userlist ;}

4. Struts configuration file: struts. xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.1.7 // en" http://struts.apache.org/dtds/struts-2.1.7.dtd "> <struts> <! -- Struts2 development mode --> <constant name = "struts. devmode" value = "true"/> <! -- In JSON format, the package's extends must be extends = "JSON-Default" --> <! -- And must use struts2 JSON-lib, struts2-json-plugin package --> <! -- Asynchronous submission is adopted. The type of result is "JSON ", and the result node value is null --> <package name = "default" namespace = "/test" extends = "JSON-Default"> <! -- The client request uses DMI (dynamic call) --> <action name = "input_user" class = "com. agcro. jquery. action. useraction "> <result name =" input_user ">/input_user.jsp </result> <result name =" El "type =" JSON "> </result> </Action> <! -- Client request (non-dynamic call) --> <action name = "userinfo" class = "com. agcro. jquery. action. useraction "method =" loaduserinfo "> <result name =" userinfo "type =" JSON "> </result> </Action> <action name =" userinfolist "class =" com. agcro. jquery. action. useraction "method =" loaduserinfolist "> <result name =" userinfolist "type =" JSON "> </result> </Action> <action name =" add_user "class =" com. agcro. jquery. action. useraction "method =" Addu Ser "> <result name =" add_success "type =" JSON "> </result> </Action> <action name =" load_alluser "class =" com. agcro. jquery. action. useraction "method =" loadalluser "> <result name =" user "type =" JSON "> </result> </Action> <! -- Display without asynchronous submission --> <action name = "load_alluser_jump" class = "com. agcro. jquery. action. useraction "method =" loadalluser "> <result name =" user ">/user. JSP </result> </Action> </package> </struts>

5. Service Class: userservice. Java

public class UserService {    public List<UserInfo> getUser(){        Connection conn=Db.createConnection();        String sql="select * from user";        UserInfo userInfo =null;        List<UserInfo> users =new ArrayList<UserInfo>();        try{            PreparedStatement ps=Db.prepare(conn, sql);            ResultSet rs= ps.executeQuery();            while(rs.next()){                userInfo = new UserInfo();                userInfo.setId(rs.getInt("id"));                userInfo.setName(rs.getString("name"));                users.add(userInfo);            }            Db.close(rs);            Db.close(ps);            Db.close(conn);        }catch (Exception e){            e.printStackTrace();        }        return users;    }    public void addUser(UserInfo userInfo){        Connection conn=Db.createConnection();        String sql="insert into user (id, name) values(?,?)";        try{            PreparedStatement ps=Db.prepare(conn, sql);            ps.setInt(1, userInfo.getId());            ps.setString(2, userInfo.getName());            ps.executeUpdate();            Db.close(ps);            Db.close(conn);        }catch (Exception e){            e.printStackTrace();        }    }}

6. jsp: User. jsp after non-asynchronous submission

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib uri="/struts-tags" prefix="s" %>

7. Application configuration file that everyone knows: Web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"           version="2.5">    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>      </welcome-file-list>    <filter>        <filter-name>struts2</filter-name>        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping></web-app>

8. Database Access: DB. Java

Package COM. agcro. jquery. util; import Java. SQL. *;/*** created by intellij idea. * userinfo: anyx * Date: 12-4-15 * Time: * to change this template use file | Settings | file templates. */public class dB {public static connection createconnection () {connection conn = NULL; string url = "JDBC: mysql: // localhost/test"; string username = "root "; string Password = "123"; try {class. forname ("com. mySQL. JDBC. driver "); Conn = drivermanager. getconnection (URL, username, password);} catch (exception e) {e. printstacktrace ();} return conn;} public static preparedstatement prepare (connection Conn, string SQL) {preparedstatement PS = NULL; try {PS = Conn. preparestatement (SQL);} catch (exception e) {e. printstacktrace ();} return pS;} public static void close (connection conn) {If (conn = NULL) {return;} Try {Conn. close (); Conn = NULL;} catch (exception e) {e. printstacktrace () ;}} public static void close (preparedstatement PS) {try {ps. close (); PS = NULL;} catch (exception e) {e. printstacktrace () ;}} public static void close (resultset RS) {try {Rs. close (); RS = NULL;} catch (exception e) {e. printstacktrace ();}}}

My project structure:



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.