环境:
操作系统: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";
例如:
3.同样的由于返回的是json数据,所以result的类型也必须采用json;
注意:struts2只能在引入json-lib,struts2-json-plugin包时,result的type属性设定json才不会报错:
4.针对异步提交,action的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" %>
请输入用户:
input_user:
$(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);
}
});
/*$.getJSON("/test/input_user!queryHello", function (data) {
//通过.操作符可以从data.hello中获得Action中hello的值
$("#allUser").html("输出了: " + data.hello);
});*/
});
$("#msgUserInfo").click(function () {
$.ajax({
url:'/test/userInfo!loadUserInfo',
type:'post',
data:"{}",
dataType:'json',
success:function (data) {
$("#allUser").append("输出了:id:" + data.userInfo.id + ", name: " + data.userInfo.name + "");
}
});
});
$("#msgUserInfoList").click(function () {
$.ajax({
url:'/test/userInfoList.action',
type:'post',
data:"{}",
dataType:'json',
success:function (data) {
/*$.each(data.userList, function(i, value){
$("#allUser").append("输出了:id:"+value.id+", name: "+value.name+"");
});*/
$(data.userList).each(function (i, value) {
$("#allUser").append("输出了:id:" + value.id + ", name: " + value.name + "");
});
}
});
});
$("#addUser").click(function () {
//必须先对提交表单数据数据进行序列化,采用jQuery的serialize()方法
var params = $("#subUserForm").serialize();
$.ajax({
url:'/test/add_user.action',
type:'post',
data:params,
dataType:'json',
success:function (data) {
/*$.each(data.userList, function(i, value){
$("#allUser").append("输出了:id:"+value.id+", name: "+value.name+"");
});*/
$(data.userList).each(function (i, value) {
$("#allUser").append("输出了:id:" + value.id + ", name: " + value.name + "");
});
}
});
});
$("#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("输出了:id:" + value.id + ", name: " + value.name + "");
});*/
$(data.userList).each(function (i, value) {
$("#allUser").append("输出了:id:" + value.id + ", name: " + value.name + "");
});
}
});
});
});
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 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() {
/*userInfo = new UserInfo();
userInfo.setId(7);
userInfo.setName("张7");*/
//如果是异步提交json格式,必须先在js中对提交的表单form进行序列化
//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 getUserList() {
return userList;
}
public void setUserList(List userList) {
this.userList = userList;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
private UserInfo userInfo;
private List userList;
}
4.Struts配置文件:struts.xml
/input_user.jsp
/user.jsp
5.Service类:UserService.java
public class UserService {
public List getUser(){
Connection conn=Db.createConnection();
String sql="select * from user";
UserInfo userInfo =null;
List users =new ArrayList();
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" %>
|
|
index.jsp
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
8.访问数据库类:Db.java
package com.agcro.jquery.util;
import java.sql.*;
/**
* Created by IntelliJ IDEA.
* UserInfo: Anyx
* Date: 12-4-15
* Time: 下午4:44
* 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();
}
}
}