标签:
来自:http://blog.csdn.net/thinkscape/article/details/7467153
环境:
操作系统:Windows 7
应用程序服务器:apache-tomcat-7.0.11
开发工具:IntelliJ IDEA 11.1.1
Java版本:Java(TM) SE Runtime Environment (build 1.7.0_03-b05)
Struts版本:struts-2.2.1.1
jQuery版本:1.7.2
MySql版本: 5.5.16 MySQL Community Server (GPL)
mysql-connector-java:5.1.15
2013年4月16日注:本例中采用的JSON数据格式,推荐使用性能更好的jackson进行序列化,不要使用json-lib
关键点:
1.引入包:struts2对数据进行json序列化,必须要用到struts2的json-lib,struts2-json-plugin包;
2.json数据处理:异步提交的数据采用json格式,struts2-json-plugin会对数据进行json处理,所以struts2配置文件struts.xml中的package节点的extends必须是:extends="json-default";
例如:<package name="default" namespace="/test" extends="json-default">
3.同样的由于返回的是json数据,所以result的类型也必须采用json;
注意:struts2只能在引入json-lib,struts2-json-plugin包时,result的type属性设定json才不会报错:<result name="userInfo" type="json"></result>
4.针对异步提交,action的result节点值应该为空,即不能再转向(例如:只能为<result name="userInfo" type="json"></result>);
时序:
绿色代表客户端请求;紫色代表从数据库返回到客户端。
jsp-----(表单提交)---->jQuery------(ajax异步)----->Struts2-----(action取得json数据)----->调用service------->其它(spring,hibernate等)-----(model)----->DB
DB----(model)------>hibernate,spring--------->service-------Struts2(action,result)------->jQuery(ajax)---------->jsp
代码:
1. 入口jsp:input_user.jsp
- <%--
- Created by IntelliJ IDEA.
- User: Anyx
- Date: 12-4-15
- Time: 下午3:46
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title></title>
- <script type="text/javascript" src="/js/jquery-1.7.2.js"></script>
- <script type="text/javascript" src="/js/myJs.js"></script>
- </head>
- <body>
- <div>
- 请输入用户:
- </div>
- <div>
- <form id="subUserForm">
- <input type="text" name="userInfo.id" id="id"/>
- <input type="text" name="userInfo.name" id="name"/>
- </form>
- </div>
- <div>
- <input id="addUser" type="button" value="添加"/>
- <input id="users" type="button" value="所有用户"/>
- <a href="/test/load_allUser_jump.action">所有用户:非异步方式</a>
- <input id="msg" type="button" value="hello"/>
- <input id="msgUserInfo" type="button" value="userInfo"/>
- <input id="msgUserInfoList" type="button" value="userInfoList"/>
- </div>
- <div id="allUser">
- input_user:
- </div>
- </body>
- </html>
2. jQuery文件:myJs.js
- $(document).ready(function () {
- $("#msg").click(function () {
- $.ajax({
- url:‘/test/input_user!queryHello‘,
- type:‘POST‘,
- data:"{}",
- dataType:‘json‘,
- success:function (data) {
- $("#allUser").append("输出了:id:" + data.hello);
- }
- });
-
- });
-
- $("#msgUserInfo").click(function () {
- $.ajax({
- url:‘/test/userInfo!loadUserInfo‘,
- type:‘post‘,
- data:"{}",
- dataType:‘json‘,
- success:function (data) {
- $("#allUser").append("<div>输出了: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) {
-
- $(data.userList).each(function (i, value) {
- $("#allUser").append("<div>输出了:id:" + value.id + ", name: " + value.name + "</div>");
- });
-
- }
- });
- });
-
- $("#addUser").click(function () {
-
- var params = $("#subUserForm").serialize();
- $.ajax({
- url:‘/test/add_user.action‘,
- type:‘post‘,
- data:params,
- dataType:‘json‘,
- success:function (data) {
-
- $(data.userList).each(function (i, value) {
- $("#allUser").append("<div>输出了:id:" + value.id + ", name: " + value.name + "</div>");
- });
-
- }
- });
- });
-
- $("#users").click(function () {
- $.ajax({
- url:‘/test/load_allUser.action‘,
- type:‘post‘,
- data:"{}",
- dataType:‘json‘,
- success:function (data) {
-
- $(data.userList).each(function (i, value) {
- $("#allUser").append("<div>输出了:id:" + value.id + ", name: " + value.name + "</div>");
- });
-
- }
- });
- });
- });
3.action类: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 "hel";
- }
-
- public String loadUserInfo() {
- userInfo = new UserInfo();
- userInfo.setId(3);
- userInfo.setName("取得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("取得userInfo3");
-
- userList.add(u1);
- userList.add(u2);
- userList.add(u3);
- return "userInfoList";
- }
-
-
- public String addUser() {
-
-
-
-
- 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 userInfo) {
- this.userInfo = userInfo;
- }
-
- private UserInfo userInfo;
- private List<UserInfo> userList;
- }
4.Struts配置文件: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>
-
- <constant name="struts.devMode" value="true"/>
-
-
-
-
- <package name="default" namespace="/test" extends="json-default">
-
- <action name="input_user" class="com.agcro.jquery.action.UserAction">
- <result name="INPUT_USER">/input_user.jsp</result>
- <result name="hel" type="json"></result>
- </action>
-
-
- <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="addUser">
- <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>
-
-
- <action name="load_allUser_jump" class="com.agcro.jquery.action.UserAction" method="loadAllUser">
- <result name="USER">/user.jsp</result>
- </action>
-
- </package>
- </struts>
5.Service类: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
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <html>
- <head>
- <title></title>
- </head>
- <body>
- <div id="u">
- <s:iterator value="userList" var="c">
- <s:property value="#c.id"/> |
- <s:property value="#c.name"/> |
- </br>
- </s:iterator>
- </div>
-
- </body>
- </html>
7.每个人都知道的应用程序配置文件: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.访问数据库类:Db.java
- package com.agcro.jquery.util;
- import java.sql.*;
- 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();
- }
- }
-
- }
我的工程结构:
struts2+jQuery+ajax调用演示
标签:
原文地址:http://www.cnblogs.com/thounderstorm/p/4516674.html