码迷,mamicode.com
首页 > 编程语言 > 详细

java--easyUI+struts+JSP实现简单的增删查改(增)

时间:2016-06-05 13:52:43      阅读:705      评论:0      收藏:0      [点我收藏+]

标签:

1.entity类

技术分享
package com.xiaoxiong.entity;

public class Dept {
    private Integer deptno;
    private String dname;
    
    
    public Integer getDeptno() {
        return deptno;
    }
    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }
    public String getDname() {
        return dname;
    }
    public void setDname(String dname) {
        this.dname = dname;
    }
    
}
Dept
技术分享
package com.xiaoxiong.entity;

public class Emp {
    private Integer id;
    private String uname;
    private Integer age;
    private Double salary;
    private Integer deptno;
    
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Integer getDeptno() {
        return deptno;
    }
    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }
    public Integer getId() {
        return id;
    }
}
Emp

2.数据库连接工具类

技术分享
package com.xiaoxiong.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectUtil {
    //定义连接数据库参数
    private static String drivers = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/dbtest";
    private static String user = "root";
    private static String password = "a123456";
    private static Connection conn = null;
    
    /**
     * 连接数据库
     * @return
     */
    public static Connection getConn(){
        try {
            //加载驱动
            Class.forName(drivers);
            
            //连接数据库
            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    /**
     * 关闭数据库
     * @param conn
     */
    public static void close(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
}
ConnectUtil

3.sql逻辑DAO类

技术分享
package com.xiaoxiong.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.xiaoxiong.util.ConnectUtil;

public class BaseDao {
    
    //定义数据库变量
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    
    //连接数据库
    public void init(){
        conn = ConnectUtil.getConn();
    }
    
    /**
     * 执行查询语句
     * @param sql
     * @param parameters
     * @return
     */
    public ResultSet query(String sql, Object...parameters){
        //连接数据库
        init();
        //定义list集合存储查询返回的结果
        System.out.println("=====查询SQL为:"+sql);
        try {
            //预编译sql语句
            ps = conn.prepareStatement(sql);
            
            //为sql语句传值
            for(int i=1; i<=parameters.length; i++){
                ps.setObject(i, parameters[i-1]);
            }
            
            //执行sql语句
            rs = ps.executeQuery();
            
        } catch (SQLException e) {
            e.printStackTrace();
        } 
        return rs;
    }
    
    /**
     * 执行非查询语句
     * @param sql
     * @param parameters
     * @return
     */
    public int update(String sql, Object...parameters){
        init();
        
        int num = 0;
        
        try {
            ps = conn.prepareStatement(sql);
            //为sql语句传值
            for(int i=1; i<=parameters.length; i++){
                ps.setObject(i, parameters[i-1]);
            }
            
            num = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return num;
    }
    
    /**
     * 查询数据总数
     * @param sql
     * @param parameters
     * @return
     */
    public int getCount(String sql, Object...parameters){
        init();
        int count = 0;
        
        try {
            ps = conn.prepareStatement(sql);
            for(int i=1; i<=parameters.length; i++){
                ps.setObject(i, parameters[i-1]);
            }
            rs = ps.executeQuery();
            rs.next();
            count = rs.getInt(1);
            
        } catch (SQLException e) {
            e.printStackTrace();
        } 
        
        return count;
    }
    
    /**
     * 关闭数据库
     */
    public void close(){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            ConnectUtil.close(conn);
        }
    }
}
BaseDao
技术分享
package com.xiaoxiong.Dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xiaoxiong.entity.Dept;

public class DeptDao extends BaseDao {
    
    /**
     * 查询部门信息
     * @return
     */
    public List<Dept> getDeptList(){
        ResultSet rs = null;
        List<Dept> list = new ArrayList<Dept>();
        
        StringBuffer sql = new StringBuffer();
        sql.append("select deptno,dname from dept ");
        
        rs = this.query(sql.toString());
        try {
            while(rs.next()){
                Dept dept = new Dept();
                dept.setDeptno(rs.getInt("deptno"));
                dept.setDname(rs.getString("dname"));
                
                list.add(dept);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return list;
    }
}
DeptDao
技术分享
package com.xiaoxiong.Dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xiaoxiong.entity.Emp;

public class EmpDao extends BaseDao {
    public ResultSet rs = null;
    /**
     * 分页查询用户信息
     * @param page    页数
     * @param rows    每页显示的行数
     * @return list 结果集
     */
    public List<Emp> searchPage(int page, int rows,String ename, int deptno){
        List<Emp> list = new ArrayList<Emp>();
        StringBuffer sql = new StringBuffer();
        //sql语句
        sql.append("SELECT e.id,e.uname,e.age,e.salary,e.deptno from emp e ");
        //计算起始行
        int startRows = (page-1)*rows;
        
        int countRows = 0;
        
        //调用query()查询用户列表
        if(ename == null){
            //求最大数据行数
            countRows = this.maxRows(deptno);
            //三元运算判断起始值是否大于最大行数
            startRows=startRows>countRows?countRows:startRows;
            sql.append("where deptno=? ");
            sql.append("limit ?,? ");
            //测试
            System.out.println("=====>sql语句为:"+sql.toString());
            rs = this.query(sql.toString(),deptno,startRows,rows);
        }else{
            countRows = this.maxRowsByName(ename, deptno);
            sql.append("where name like ? and deptno=? ");
            sql.append("limit ?,? ");
            //测试
            System.out.println("=====>sql语句为:"+sql.toString());
            
            rs = this.query(sql.toString(),"%"+ename+"%",deptno,startRows,rows);
        }
        try {
            //将rs结果集中的数据遍历出来存入emp实例中
            while(rs.next()){
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setUname(rs.getString("uname"));
                emp.setAge(rs.getInt("age"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setDeptno(rs.getInt("deptno"));
                
                //加入list集合中
                list.add(emp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return list;
    }
    
    /**
     * 新增员工模块
     * @param emp
     * @return
     */
    public int addEmp(Emp emp){
        StringBuffer sql = new StringBuffer();
        sql.append("INSERT INTO emp(uname,age,salary,deptno) VALUES(?,?,?,?) ");
        
        return this.update(sql.toString(),emp.getUname(),emp.getAge(),emp.getSalary(),emp.getDeptno());
    }
    
    /**
     * 修改员工信息模块
     * @param emp
     * @return
     */
    public int updateEmp(Emp emp){
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE emp SET uname=?,age=?,salary=?,deptno=? WHERE id=? ");
        
        return this.update(sql.toString(), emp.getUname(),emp.getAge(),emp.getSalary(),emp.getDeptno(),emp.getId());
    }
    
    /**
     * 删除员工信息
     * @param id
     * @return
     */
    public int deleteEmp(Integer id){
        StringBuffer sql = new StringBuffer();
        sql.append("delete from emp where id=? ");
        
        return this.update(sql.toString(), id);
    }
    
    /**
     * 通过Id查询用户信息
     * @param id
     * @return
     */
    public List<Emp> queryById(Integer id){
        List<Emp> list = new ArrayList<Emp>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT e.id,e.uname,e.age,e.salary,e.deptno from emp e ");
        sql.append("where id=? ");
        
        rs = this.query(sql.toString(), id);
        try {
            //将rs结果集中的数据遍历出来存入emp实例中
            while(rs.next()){
                Emp emp = new Emp();
                emp.setUname(rs.getString("uname"));
                emp.setAge(rs.getInt("age"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setDeptno(rs.getInt("deptno"));
                
                //加入list集合中
                list.add(emp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } 
        
        return list;
    }
    
    /**
     * 最大条数
     * @param deptno
     * @return
     */
    public int maxRows(int deptno){
        StringBuffer sql = new StringBuffer();
        
        sql.append("select count(*) from emp where deptno=? ");
        System.out.println("========maxRows的SQL:"+sql);
        return this.getCount(sql.toString(),deptno);
        
    }
    
    public int maxRowsByName(String ename,int deptno){
        StringBuffer sql = new StringBuffer();
        
        sql.append("select count(*) from emp ");
        sql.append("where ename like ? and deptno=? ");
        
        return this.getCount(sql.toString(),"%"+ename+"%", deptno);
    }
    
}
EmpDao

4.Action类

技术分享
package com.xiaoxiong.action;

import java.util.List;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xiaoxiong.Dao.DeptDao;
import com.xiaoxiong.entity.Dept;

public class DeptAction extends ActionSupport {
    DeptDao dao = new DeptDao();
    
    public String deptList(){
        
        List<Dept> list = dao.getDeptList();
//        ServletActionContext.getRequest().setAttribute("deptlist", list);
        ActionContext.getContext().put("deptlist", list);
        System.out.println("执行deptList方法----"+list.toArray());
        
        return this.SUCCESS;
    }
    
}
DeptAction
技术分享
package com.xiaoxiong.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.xiaoxiong.Dao.EmpDao;
import com.xiaoxiong.entity.Emp;

public class EmpAction extends ActionSupport implements ModelDriven<Emp> {
    //定义一个emp参数
    private Emp emp;
    //页面数
    private Integer page;
    //行数
    private Integer rows;
    //模糊查询的条件
    private String ename;
    
    //实例化一个EmpDao类
    EmpDao dao = new EmpDao();
    
    public String searchPage() throws IOException{
        System.out.println("执行查询语句"+emp.getDeptno());
        List<Emp> list = new ArrayList<Emp>();
        int count = 0;
        list = dao.searchPage(page, rows, ename,emp.getDeptno());
        if(ename==null){
            count = dao.maxRows(emp.getDeptno());
        }else{
            count = dao.maxRowsByName(ename, emp.getDeptno());
        }
        
        //map存储结果集
        Map map = new HashMap();
        map.put("total", count);
        map.put("rows", list);
        
        //将数据转换为json格式
        String json = new Gson().toJson(map);
        
        System.out.println("json数据==="+json);
        //将json数据传送给页面
        ServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        
        response.getWriter().println(json);
        
        return this.NONE;
    }
    
    
    @Override
    public Emp getModel() {
        emp = new Emp();
        return emp;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }
    
}
EmpAction

5.struts.xml文件的配置

技术分享
<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD 这是一个用来描述XML文件能写什么标签不能写什么标签的规则文件 -->
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="deptPackage" extends="struts-default" namespace="/">
            <action name="deptList" class="com.xiaoxiong.action.DeptAction" method="deptList">
                <result name="success">/index.jsp</result>
            </action>
    </package>

    <package name="empPackage" extends="struts-default" namespace="/">
        <action name="searchPage" class="com.xiaoxiong.action.EmpAction" method="searchPage"></action>
    </package>
</struts> 
struts.xml

6.easyUI实现JSP页面

技术分享
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%
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>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">
    
    <!-- Easyui主题CSS -->
    <link rel="stylesheet" href="style/easyui/ui-pepper-grinder/easyui.css" type="text/css"></link>
    <!-- 图标CSS -->
    <link rel="stylesheet" href="style/easyui/icon.css" type="text/css"></link></head>
    
    <script type="text/javascript" src="script/jquery.min.js"></script>
    <script type="text/javascript" src="script/jquery.easyui.min.js"></script>
    <style>
        .tab-body{
            overflow: hidden;
                
        }
    </style>
    <script>
        $(function(){
            $("#treeFunctions").tree({
                onClick : function(node){
                    console.info(node);//浏览器控制台打印节点数据
                    var deptno = node.attributes.deptno;
                    $("#grdEmp").datagrid("load",{
                        "deptno":deptno  //将deptno当值传送给服务端
                    });
                }
            });
        });
    </script>
  </head>
   
  <body class="easyui-layout">
      <div region="north" style="height: 100px">
          <div style="background-color: red"></div>
      </div>
      
      <div region="west" title="系统列表" split=true style="width: 300px">
          <div class="easyui-accordion" fit="true" border=false>
              <div title="系统管理平台">
                  <ul class="easyui-tree" id="treeFunctions">
                      <li><span>部门信息</span>
                          <ul id="Departments">
                            <!-- Easyui中为树的节点自定义属性使用data-options -->
                            <c:forEach items="${deptlist }" var="d">
                                <li data-options="attributes:{deptno :${d.deptno } }"><span>${d.dname }</span></li>
                            </c:forEach>
                        </ul>
                      </li>
                  </ul>
              </div>
          </div>
      </div>
      <div region="center">
          <table id="grdEmp" pagination=true pageSize="5" pageList="[5]" class="easyui-datagrid" toolbar="#tb"
          fit=true url="/managerProject/searchPage" >
              <thead>
                  <tr>
                    <th width="100" field="id">编号</th>
                    <th width="100" field="uname">姓名</th>
                    <th width="100" field="age">年龄</th>
                    <th width="100" field="salary">工资</th>
                    <th width="100" field="deptno">部门</th>
                </tr>
              </thead>
          </table>
      </div>    
      <div region="center">
          <div class="easyui-tabs" id="tabsMain" fit="true" border="false">
              <div title="首页" ></div>
          </div>
      </div>
      <div id="tb">
        <input id="txtEname" class="easyui-textbox"/>
        <a id="btnQuery" href="#" class="easyui-linkbutton" data-options="iconCls:‘icon-search‘">查询</a>
        <a id="btnAdd" href="#" class="easyui-linkbutton" iconCls="icon-add">新增</a>
          <a id="btnEdit" href="#" class="easyui-linkbutton" iconCls="icon-edit">修改</a>
          <a id="btndelete" href="#" class="easyui-linkbutton" iconCls="icon-remove">删除</a>
        
    </div>
  </body>
</html>
index.jsp

 

java--easyUI+struts+JSP实现简单的增删查改(增)

标签:

原文地址:http://www.cnblogs.com/rsdqc/p/5560508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!