Struts2+Ajax+DTGrid简单展示

最近一直在忙这件事,还是配置json的问题,还是解决了,DTGrid还是一款不错的开源产品。

UserInfo.java:

package dao;

public class UserInfo {
    
    private int id;
    
    private String name;
    
    private int age;
    
    private double salary;
    
    
    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    
}

UserService.java:

package service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.Db;

import dao.UserInfo;

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"));
                    userInfo.setAge(rs.getInt("age"));
                    userInfo.setSalary(rs.getDouble("salary"));
                    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 tablex (id,name,age,salary) values(?,?,?,?)";

            try{
                PreparedStatement ps=Db.prepare(conn, sql);
                ps.setInt(1, userInfo.getId());
                ps.setString(2, userInfo.getName());
                ps.setInt(3, userInfo.getAge());
                ps.executeUpdate();

                Db.close(ps);
                Db.close(conn);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
}

Db.java:

package util;

import java.sql.*;

public class Db {
    public static Connection createConnection(){
        Connection conn=null;
        String url="jdbc:mysql://172.11.8.196:3306/test";
        String username="root";
        String password="root";

        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();
        }
    }

}

UserAction.java:

package action;

import java.util.ArrayList;
import java.util.List;

import service.UserService;

import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionSupport;

import dao.UserInfo;

public class UserAction extends ActionSupport {

    UserService us = new UserService();

    private UserInfo userInfo;
    private List<UserInfo> userList;
    
    public String loadUserInfo() {
        userInfo = new UserInfo();
        userInfo.setId(3);
        userInfo.setName("Info");
        userInfo.setAge(11);
        userInfo.setSalary(100);
        return "userInfo";
    }

    public String loadUserInfoList() {
        userList=us.getUser();
       /* userList = new ArrayList<UserInfo>();

        UserInfo u1 = new UserInfo();
        u1.setId(1);
        u1.setName("Info1");
        u1.setAge(12);
        
        UserInfo u2 = new UserInfo();
        u2.setId(2);
        u2.setName("Info2");
        u2.setAge(13);
        
        UserInfo u3 = new UserInfo();
        u3.setId(3);
        u3.setName("Info3");
        u3.setAge(14);
        
        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";
    }

    public List<UserInfo> getUserList() {
        return userList;
    }

    public void setUserList(List<UserInfo> userList) {
        this.userList = userList;
    }
    @JSON(serialize=false)
    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

}

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的开发模式-->
    <constant name="struts.devMode" value="false"/>

    <!--采用json数据格式,package的extends必须是extends="json-default"-->
    <!--并且必须要用到struts2的json-lib,struts2-json-plugin包-->
    <!--采用异步提交方式,result的type="json",并且result节点值为空-->
    <package name="default"  extends="json-default">
  
        <!--客户端请求(非动态调用)-->
        <action name="userInfo" class="action.UserAction" method="loadUserInfo">
            <result name="userInfo" type="json"></result>
        </action>

        <action name="userInfoList" class="action.UserAction" method="loadUserInfoList">
            <result name="userInfoList" type="json"></result>
        </action>


        <action name="add_user" class="action.UserAction" method="addUser">
            <result name="ADD_SUCCESS" type="json"></result>
        </action>

        <action name="load_allUser" class="action.UserAction" method="loadAllUser">
            <result name="USER" type="json"></result>
        </action>

    </package>
</struts>

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>用户信息显示</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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<!-- jQuery -->
    <script type="text/javascript" src="dtGrid/dependents/jquery/jquery.min.js"></script>
    <!-- bootstrap -->
    <script type="text/javascript" src="dtGrid/dependents/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="dtGrid/dependents/bootstrap/css/bootstrap.min.css" />
    <!-- font-awesome -->
    <link rel="stylesheet" type="text/css" href="dtGrid/dependents/fontAwesome/css/font-awesome.min.css" media="all" />
    <!-- dtGrid -->
    <script type="text/javascript" src="dtGrid/jquery.dtGrid.min.js"></script>
    <script type="text/javascript" src="dtGrid/i18n/en.js"></script>
    <script type="text/javascript" src="dtGrid/i18n/zh-cn.js"></script>
    <script type="text/javascript" src="dtGrid/i18n/zh-tw.js"></script>
    <link rel="stylesheet" type="text/css" href="dtGrid/jquery.dtGrid.min.css" />
    <!-- datePicker -->
    <script type="text/javascript" src="dtGrid/dependents/datePicker/WdatePicker.js" defer="defer"></script>
    <link rel="stylesheet" type="text/css" href="dtGrid/dependents/datePicker/skin/WdatePicker.css" />
    <link rel="stylesheet" type="text/css" href="dtGrid/dependents/datePicker/skin/default/datepicker.css" />
    
<%-- <script type="text/javascript"
    src="${pageContext.request.contextPath}/js/jquery-1.7.2.js">
    
</script> --%>
<script type="text/javascript">
var datas = new Array();
$(document).ready(function(){
    $.ajax({
            type : "post",
            url : "userInfoList.action",
            dataType : "json",
        /*     async : false, */
            success : function(data) {
                var arr=eval(data.userList);
                 $.each(arr,function(i){
                    var user = new Object();
                    user.user_id=arr[i].id;
                    user.user_name=arr[i].name;
                    user.user_age=arr[i].age;
                    user.user_salary=arr[i].salary;
                    user.time = new Date(Math.floor(Math.random()*1096588800000)+315504000000);
                    user.time_stamp_s = Math.floor((Math.floor(Math.random()*1096588800000)+315504000000)/1000);
                       user.time_stamp_ms = Math.floor(Math.random()*1096588800000)+315504000000;
                    user.string_date = $.fn.DtGrid.tools.dateFormat(new Date(Math.floor(Math.random()*1096588800000)+315504000000), ‘yyyy-MM-dd‘);
                    user.string_time = $.fn.DtGrid.tools.dateFormat(new Date(Math.floor(Math.random()*1096588800000)+315504000000), ‘yyyy-MM-dd hh:mm:ss‘);
                    datas.push(user);
                    //return datas;    
                });                                    
            }
        });
});
</script>
</head>

<body>
    <script type="text/javascript">
                var dtGridColumns_2_1_1 = [
                    {id:‘user_id‘, title:‘Id‘, type:‘number‘, columnClass:‘text-center‘},
                    {id:‘user_name‘, title:‘姓名‘, type:‘string‘,columnClass:‘text-center‘},
                    {id:‘user_age‘, title:‘年龄‘, type:‘number‘, columnClass:‘text-center‘},
                    {id:‘user_salary‘, title:‘薪水‘, type:‘number‘, columnClass:‘text-center‘},
                    {id:‘time‘, title:‘日期对象‘, type:‘date‘, format:‘yyyy-MM-dd hh:mm:ss‘, columnClass:‘text-center‘, hideType:‘md|sm|xs‘},
                    {id:‘time_stamp_s‘, title:‘秒级时间戳‘, type:‘date‘, format:‘yyyy-MM-dd hh:mm:ss‘, otype:‘time_stamp_s‘, columnClass:‘text-center‘, hideType:‘lg|md|sm|xs‘},
                    {id:‘time_stamp_ms‘, title:‘毫秒级时间戳‘, type:‘date‘, format:‘yyyy-MM-dd hh:mm:ss S‘, otype:‘time_stamp_ms‘, columnClass:‘text-center‘, hideType:‘lg|md|sm|xs‘},
                    {id:‘string_date‘, title:‘日期格式字符串‘, type:‘date‘, format:‘yyyy-MM-dd‘, otype:‘string‘, oformat:‘yyyy-MM-dd‘, columnClass:‘text-center‘, hideType:‘lg|md|sm|xs‘},
                    {id:‘string_time‘, title:‘时间格式字符串‘, type:‘date‘, format:‘yyyy-MM-dd hh:mm:ss‘, otype:‘string‘, oformat:‘yyyy-MM-dd hh:mm:ss‘, columnClass:‘text-center‘, hideType:‘lg|md|sm|xs‘}                
                ];
                var dtGridOption_2_1_1 = {
                    lang : ‘zh-cn‘,
                    ajaxLoad : false,
                    exportFileName : ‘用户列表‘,
                    datas : datas,
                    columns : dtGridColumns_2_1_1,
                    gridContainer : ‘dtGridContainer_2_1_1‘,
                    toolbarContainer : ‘dtGridToolBarContainer_2_1_1‘,
                    tools : ‘‘,
                    pageSize : 10,
                    pageSizeLimit : [10, 20, 50]
                };
                var grid_2_1_1 = $.fn.DtGrid.init(dtGridOption_2_1_1);
                $(function(){
                    grid_2_1_1.load();
                });
                </script>
                
                <div id="dtGridContainer_2_1_1" class="dt-grid-container"></div>
                <div id="dtGridToolBarContainer_2_1_1" class="dt-grid-toolbar-container"></div>
</body>
</html>
 

运行效果图:

技术分享

技术分享

项目图录:

技术分享(图中红色错误是因为引入的dtGrid文件引入的jquery.min.js文件,无影响,如果实在看不惯可设置MyEclipse解除js检验)

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。