[jQuery EasyUI系列] 创建增删改查应用

by admin on 2019年9月5日
<script type="text/javascript">

  function formatProgress(value){
      if (value){
       var s = '<div style="width:100%;border:1px solid #ccc">' +
         '<div style="width:' + value + '%;background:#cc0000;color:#fff">' + value + '%' + '</div>'
         '</div>';
       return s;
      } else {
       return '';
      }
  }
  var editingId;
  function deleteRow(){
   if (editingId != undefined){
    $('#tg').treegrid('select', editingId);
    return;
   }
   var row = $('#tg').treegrid('getSelected');
   if (row){
    editingId = row.id
    $('#tg').treegrid('remove', editingId);
    $('#tg').treegrid('reloadFooter');
   }
   $(".actionbtn").toggleClass("l-btn-disabled");
  }
  function edit(){
   if (editingId != undefined){
    $('#tg').treegrid('select', editingId);
    return;
   }
   var row = $('#tg').treegrid('getSelected');
   if (row){
    editingId = row.id
    $('#tg').treegrid('beginEdit', editingId);
   }
   $(".actionbtn").toggleClass("l-btn-disabled");
  }
  function insert(){
   if (editingId != undefined){
    $('#tg').treegrid('select', editingId);
    return;
   }
   /**/
   var rows = $('#tg').treegrid('getChildren');
   editingId = rows.length+1;
   var row = null;
   var _data = {"id":editingId,"name":"new name","persons":0,"begin":"3/19/2010","end":"3/20/2010","progress":10};
   var _parentId = 0;
   var row = $('#tg').treegrid('getSelected');
   if (row){
    $('#tg').treegrid('expand',row.id);
    _parentId = row.id;
   }else{
    var root = $('#tg').treegrid('getRoot');
    _parentId = null;
   }

   $('#tg').treegrid('append',{
    parent: _parentId,  // 这里指定父级标识就可以了
    data: [_data]
   });

   $('#tg').treegrid('beginEdit',_data.id);
   $(".actionbtn").toggleClass("l-btn-disabled");
  }
  function save(){
   if (editingId != undefined){
    var t = $('#tg');
    t.treegrid('endEdit', editingId);
    editingId = undefined;
    var persons = 0;
    var rows = t.treegrid('getChildren');
    for(var i=0; i<rows.length; i++){
     var p = parseInt(rows[i].persons);
     if (!isNaN(p)){
      persons += p;
     }
    }
    var frow = t.treegrid('getFooterRows')[0];
    frow.persons = persons;
    t.treegrid('reloadFooter');
    $(".actionbtn").toggleClass("l-btn-disabled");
   }
  }
  function cancel(){
   if (editingId != undefined){
    $('#tg').treegrid('cancelEdit', editingId);
    editingId = undefined;
   }
   $(".actionbtn").toggleClass("l-btn-disabled");
  }
 </script>

 <div style="margin:10px 0;">
  <a href="javascript:void(0)" disabled="disabled"  class="easyui-linkbutton actionbtn" onclick="save()">Save</a>
  <a href="javascript:void(0)" disabled="disabled" class="easyui-linkbutton actionbtn" onclick="cancel()">Cancel</a>
 </div>
<div style="margin:10px 0;">
  <a href="javascript:void(0)" class="easyui-linkbutton" onclick="edit()">Edit</a>
  <a href="javascript:void(0)" class="easyui-linkbutton" onclick="insert()">Insert</a>
  <a href="javascript:void(0)" class="easyui-linkbutton" onclick="deleteRow()">Delete</a>
 </div>
 <table id="tg" class="easyui-treegrid" title="Editable TreeGrid" style="width:700px;"
   data-options="
    iconCls: 'icon-ok',
    rownumbers: true,
    animate: true,
    collapsible: true,
    fitColumns: true,
    url: '../treegrid/treegrid_data2.json',
    idField: 'id',
    treeField: 'name',
    showFooter: true
   ">
  <thead>
   <tr>
    <th data-options="field:'name',width:180,editor:'text'">Task Name</th>
    <th data-options="field:'persons',width:60,align:'right',editor:'numberbox'">Persons</th>
    <th data-options="field:'begin',width:80,editor:'datebox'">Begin Date</th>
    <th data-options="field:'end',width:80,editor:'datebox'">End Date</th>
    <th data-options="field:'progress',width:120,formatter:formatProgress,editor:'numberbox'">Progress</th>
   </tr>
  </thead>
 </table>

一、数据采撷并稳当管理数据是网络采纳共同的画龙点睛。CRUD允许大家生育页面列表并编写数据库记录。

转自:

前言

     
明日用SpringJdbc连接了一把SQLServer,凌晨起来用SpringMVC+SpringJdbc+EasUI写了个增加和删除改查的demo,主假设熟识下SpringMVC相关知识点,如view层向Controller传参的二种办法,从Controller向view传递model的二种艺术。
在那之中从view层向controller层传递时碰着了些难点,刚开首报400、415,都以由于传递的不二秘籍后台不能分辨。

 

 

 

本文主要演示怎么样行使jQuery EasyUI达成CRUD DataGrid.

前台代码:

支出条件

     idea2016、SpringMVC4、SpringJdbc4

 

type=text/javascriptfunction
formatProgress(value){ if (value){ var s = div
style=width:100%;border:1px solid #ccc + div style=width: + value +
%;background:#cc0000;color:#f…

style=margin:10px 0;a
href=javascript:void(0) class=easyui-linkbutton onclick=edit()Edit/aa
href=javascript:void(0) class=easyui-linkbutton
onclick=insert()Insert/aa href=j…

将利用到的插件有:

图片 1图片 2

品类组织

图片 3

 

   datagrid:向客商展现列表数据

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>

     <link rel="stylesheet" type="text/css" href="../EasyUI/themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="../EasyUI/themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="../demo.css" />
    <style type="text/css">
.align-center{
    margin:0 auto;        /* 居中 这个是必须的,,其它的属性非必须 */
    width:100%;        /* 给个宽度 顶到浏览器的两边就看不出居中效果了 */

    height:300px;
    text-align:center;     /* 文字等内容居中 */
}
</style>
    <script type="text/javascript" src="../EasyUI/jquery.min.js"></script>
    <script type="text/javascript" src="../EasyUI/jquery.easyui.min.js"></script>
       <script type="text/javascript">

           var url; //提交数据的路径
           var formId; //当天要提交的Form的编号
           var dialogId; //对话框的编号




           $(function () {


               $('#ReceiveList').datagrid({
                   toolbar: [{
                       //iconCls: 'icon-remove',
                       iconCls: 'icon-cut',
                       handler: function () { deleteAdminUser(); }
                   }, '-', {
                       iconCls: 'icon-edit',
                       handler: function () { edittbUser(); }
                   }, '-', {
                       iconCls: 'icon-add',
                       handler: function () { addtbUser(); }
                   }

                   ]
               });




           });


           function pagerFilter(data) {
               if (typeof data.length == 'number' && typeof data.splice == 'function') {    // is array
                   data = {
                       total: data.length,
                       rows: data
                   }
               }
               var dg = $('#ReceiveList');
               var opts = dg.datagrid('options');
               var pager = dg.datagrid('getPager');
               pager.pagination({
                  // pageSize: 10,//每页显示的记录条数,默认为10  
                  // pageList: [5, 10, 15],//可以设置每页记录条数的列表  
                   beforePageText: '第',//页数文本框前显示的汉字  
                   afterPageText: '页    共 {pages} 页',
                   displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
                   onSelectPage: function (pageNum, pageSize) {
                       opts.pageNumber = pageNum;
                       opts.pageSize = pageSize;
                       pager.pagination('refresh', {
                           pageNumber: pageNum,
                           pageSize: pageSize
                       });
                       dg.datagrid('loadData', data);
                   }
               });
               if (!data.originalRows) {
                   data.originalRows = (data.rows);
               }
               var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
               var end = start + parseInt(opts.pageSize);
               data.rows = (data.originalRows.slice(start, end));
               return data;
           }

           $(function () {
               $('#ReceiveList').datagrid({ loadFilter: pagerFilter }).datagrid('loadData', '/ashx/RoleList.ashx?action=GetRoleList');
           });





           //  删除代码部分
           function deleteAdminUser() {
               var row = $('#ReceiveList').datagrid('getSelected');
               if (row) {
                   $.messager.confirm('删除提示', '确定要删除' + row.UserName + '吗', function (r) {
                       if (r) {
                           $.post('/ashx/RoleList.ashx', { id: row.UserID, action: 'deleteRole' }, function (data, status) {

                               if (data == "ok") {
                                   $.messager.show({
                                       title: 'success',
                                       msg: '删除成功!'
                                   });
                                   $('#ReceiveList').datagrid('reload');


                               } else {
                                   $.messager.show({
                                       title: 'Error',
                                       msg: '删除用户失败!'
                                   });
                               }
                           });
                       }
                   });
               }
               else {
                   //$.messager.show({
                   //    title: 'Error',
                   //    msg: '你没有选中行!'
                   //});
                   $.messager.alert("提示", "您没有选中任何行!");
               }
           }
           //添加
           function addtbUser() {
               $("#addtbUserDialog").dialog({
                   "title": "新添用户",
                   width: 500,
                   height: 450

               });
               $('#addtbUserDialog').dialog('open');
               $('#addForm').form('clear');

               url = '/ashx/RoleList.ashx?action=add';
               formId = "#addForm";
               dialogId = "#addtbUserDialog";
           }

           function add() {

               $(formId).form('submit', {
                   url: url,
                   onSubmit: function () {

                       return $(this).form('validate');
                   },

                   success: function (data) {


                       if (data == 'ok') {
                           $.messager.show({
                               title: 'success',
                               msg: '插入成功!'
                           });
                           // $(dialogId).dialog('close');
                           $('#ReceiveList').datagrid('reload');
                       } else {
                           $.messager.show({
                               title: 'Error',
                               msg: '插入失败!'
                           });
                       }

                       //$(dialogId).dialog('close');
                       $('#ReceiveList').datagrid('reload');
                   }
               });
           }
           //编辑
           function edittbUser() {
               $("#edittbUserDialog").dialog({
                   "title": "修改信息",
                   width: 500,
                   height: 450

               });
               var row = $('#ReceiveList').datagrid('getSelected');
               if (row) {
                   $('#edittbUserDialog').dialog('open');
                   $("#editUserName").val(row.UserName);
                   $("#editUserPassword").val(row.UserPassword);
                   $("#editNickName").val(row.NickName);
                   $("#editDeptID").val(row.DeptID);
                   $("#editPhone").val(row.Phone);

                   //  $("#UserID").combobox('setValue', row.UserID);
                   //   $('#edit').form('clear');

                   url = '/ashx/RoleList.ashx?action=edit&UserID=' + row.UserID;
                   formId = "#editForm";
                   dialogId = "#edittbUserDialog";


               }
               else {
                   $.messager.alert("提示", "您没有选中任何行!");
               }
           }

           function edit() {

               $(formId).form('submit', {
                   url: url,
                   onSubmit: function () {
                       // alert(formId);
                       return $(this).form('validate');

                   },
                   // success: successCallback
                   success: function (data) {
                       //alert(data)
                       //$.messager.show({
                       //    title: 'success',
                       //    msg: data
                       //});


                       //$.messager.alert("提示", data);

                       if (data == 'ok') {
                           $.messager.show({
                               title: 'success',
                               msg: '修改成功!'
                           });
                           $(dialogId).dialog('close');
                           $('#ReceiveList').datagrid('reload');
                       } else {
                           $.messager.show({
                               title: 'Error',
                               msg: '修改失败!'
                           });
                       }

                       //$(dialogId).dialog('close');
                       $('#ReceiveList').datagrid('reload');
                   }
               });


               //$.post('/ashx/RoleList.ashx', {action:'edit',UserID:UserID, UserName: UserID, UserPassword: UserID }, function (data, status) {

               //    if (data == "ok") {
               //        $('#ReceiveList').datagrid('reload');
               //    } else {
               //        $.messager.show({
               //            title: 'Error',
               //            msg: '删除该科室失败!'
               //        });
               //    }
               //});
           }

           //多条件查询方法
           function tsearch() {
              //  var hoistalName = $("#hoistalName").combobox("getValue");
               var UserID = $("#UserID").val();
               //alert(depName);
               $('#ReceiveList').datagrid('options').pageNumber = 1;
               $('#ReceiveList').datagrid('getPager').pagination({ pageNumber: 1 });
               $('#ReceiveList').datagrid('options').url = '/ashx/RoleList.ashx?action=search&UserID='+UserID;
               $('#ReceiveList').datagrid("reload");
           }
    </script>

</head>
<body>
   <br/>
      <div class="searchitem">
    <label>UserID:</label>
    <input type="text" id="UserID" class="easyui-validatebox" />
          <a href="#" class="easyui-linkbutton" onclick="tsearch()" >查询</a>
    </div>

 <table id="ReceiveList" title="Custom DataGrid Pager" style="width:700px;height:400px"
            data-options="rownumbers:true,singleSelect:true,pagination:true,url:'/ashx/RoleList.ashx?action=GetRoleList',method:'get',pageSize:10
            ">
        <thead>
            <tr>
                <th data-options="field:'UserID',checkbox:true,width:80">用户ID</th>
                <th data-options="field:'UserName',width:100">用户名</th>
                <th data-options="field:'UserPassword',width:80,align:'right'">用户密码</th>
                <th data-options="field:'NickName',width:80,align:'right'">昵称</th>
                <th data-options="field:'DeptID',width:240">部门ID</th>
                <th data-options="field:'Phone',width:60,align:'center'">电话</th>
            </tr>
        </thead>
    </table>


          <div id="addtbUserDialog" class="easyui-dialog" closed="true" buttons="#addtbUser-buttons" style="padding:10px 20px"> 
               <form id="addForm"  method="post">
                   <table class="align-center">
                       <tr>
                           <td> 用户名</td>
                           <td><input id="Text1"  name="UserName" class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>用户密码</td>
                           <td><input id="Password1" name="UserPassword"  class="easyui-validatebox" data-options="required:true" type="password"/></td>
                       </tr>
                        <tr>
                           <td>昵称</td>
                           <td><input id="Text2"  name="NickName" class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>部门ID</td>
                           <td><input id="Text3" name="DeptID"  class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>电话</td>
                           <td><input id="Text4" name="Phone" class="easyui-validatebox" data-options="required:true"  type="text"/></td>
                       </tr>
                   </table>

               </form>

            </div>
            <div id="addtbUser-buttons">
                <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="add()">保存</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#addtbUserDialog').dialog('close')">关闭</a>
            </div>




           <div id="edittbUserDialog" class="easyui-dialog" closed="true" buttons="#edittbUser-buttons" style="padding:10px 20px;"  >
               <form id="editForm"  method="post"   >
                <table class="align-center">
                       <tr>
                           <td> 用户名</td>
                           <td><input id="editUserName"  name="UserName" class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>用户密码</td>
                           <td><input id="editUserPassword" name="UserPassword"  class="easyui-validatebox" data-options="required:true" type="password"/></td>
                       </tr>
                        <tr>
                           <td>昵称</td>
                           <td><input id="editNickName"  name="NickName" class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>部门ID</td>
                           <td><input id="editDeptID" name="DeptID"  class="easyui-validatebox" data-options="required:true" type="text"/></td>
                       </tr>
                        <tr>
                           <td>电话</td>
                           <td><input id="editPhone" name="Phone" class="easyui-validatebox" data-options="required:true"  type="text"/></td>
                       </tr>
                   </table>

               </form>
            </div>
            <div id="edittbUser-buttons">
                <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="edit()">保存</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#edittbUserDialog').dialog('close')">关闭</a>
            </div>



</body>
</html>

花色源文件

1、pom.xml

图片 4图片 5

 1   <dependencies>
 2     <dependency>
 3       <groupId>org.springframework</groupId>
 4       <artifactId>spring-beans</artifactId>
 5       <version>4.3.6.RELEASE</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>org.springframework</groupId>
 9       <artifactId>spring-context</artifactId>
10       <version>4.3.6.RELEASE</version>
11     </dependency>
12     <dependency>
13       <groupId>org.springframework</groupId>
14       <artifactId>spring-core</artifactId>
15       <version>4.3.6.RELEASE</version>
16     </dependency>
17     <dependency>
18       <groupId>org.springframework</groupId>
19       <artifactId>spring-test</artifactId>
20       <version>4.3.6.RELEASE</version>
21     </dependency>
22     <dependency>
23       <groupId>org.springframework</groupId>
24       <artifactId>spring-web</artifactId>
25       <version>4.3.6.RELEASE</version>
26     </dependency>
27     <dependency>
28       <groupId>org.springframework</groupId>
29       <artifactId>spring-webmvc</artifactId>
30       <version>4.3.6.RELEASE</version>
31     </dependency>
32     <dependency>
33       <groupId>org.springframework</groupId>
34       <artifactId>spring-jdbc</artifactId>
35       <version>4.3.6.RELEASE</version>
36     </dependency>
37     <dependency>
38       <groupId>junit</groupId>
39       <artifactId>junit</artifactId>
40       <version>4.10</version>
41     </dependency>
42     <dependency>
43       <groupId>com.microsoft.sqlserver</groupId>
44       <artifactId>sqljdbc4</artifactId>
45       <version>4.0</version>
46     </dependency>
47     <dependency>
48       <groupId>commons-dbcp</groupId>
49       <artifactId>commons-dbcp</artifactId>
50       <version>1.4</version>
51     </dependency>
52     <dependency>
53       <groupId>com.alibaba</groupId>
54       <artifactId>fastjson</artifactId>
55       <version>1.2.12</version>
56     </dependency>
57     <dependency>
58       <groupId>com.fasterxml.jackson.core</groupId>
59       <artifactId>jackson-core</artifactId>
60       <version>2.5.0</version>
61     </dependency>
62     <dependency>
63       <groupId>com.fasterxml.jackson.core</groupId>
64       <artifactId>jackson-annotations</artifactId>
65       <version>2.5.0</version>
66     </dependency>
67     <dependency>
68       <groupId>com.fasterxml.jackson.core</groupId>
69       <artifactId>jackson-databind</artifactId>
70       <version>2.5.0</version>
71     </dependency>
72   </dependencies>

View Code

2、web.xml

图片 6图片 7

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--告知javaEE容器,有那些内容需要添加到上下文里去-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--spring 前端控制器-->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

View Code

3、jdbc.properties

sqlserver.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
sqlserver.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=testdb
sqlserver.username=sa
sqlserver.password=0

4、springmvc-servlet.xml

图片 8图片 9

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="jdbcConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${sqlserver.driver}"/>
        <property name="url" value="${sqlserver.url}"/>
        <property name="username" value="${sqlserver.username}"/>
        <property name="password" value="${sqlserver.password}"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--json数据源处理-->
    <bean id="stringConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>

    <!--启用最新的注解器、映射器-->
    <mvc:annotation-driven/>
    <!--静态资源访问-->
    <mvc:default-servlet-handler/>

    <context:component-scan base-package="com.autohome.dao"/>
    <context:component-scan base-package="com.autohome.service"/>

    <!--扫描controller-->
    <context:component-scan base-package="com.autohome.controller"/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

View Code

 

5、Dao

图片 10图片 11

@Repository
public class UserDaoImpl implements IUserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<User> listAllUser() {
        List<User> list = jdbcTemplate.query("select * from UserInfo",new User());
        return list;
    }

    public List<User> listPagedUser(int pageIndex,int pageSize){
        String sql="select top "+pageSize+" * from UserInfo where id not in (select top ("+pageSize+" * ("+pageIndex+" -1)) id from UserInfo)";
        List<User> list = jdbcTemplate.query(sql,new User());
        return list;
    }

    public int getUserCount() {

        int result = jdbcTemplate.queryForObject("select count(*) from UserInfo",Integer.class);
        return result;
    }


    public User getUserById(int id) {
        User user = jdbcTemplate.queryForObject("select * from UserInfo where id=?",new Object[]{id},new User());

        return user;
    }

    public int insertUser(final User user) {
        int result = jdbcTemplate.update("insert into UserInfo (UserName,age) VALUES (?,?)", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,user.getName());
                ps.setInt(2,user.getAge());
            }
        });

        return result;
    }

    public int updateUser(final User user) {
        int result = jdbcTemplate.update("UPDATE UserInfo set UserName=?,age=? where id=?", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,user.getName());
                ps.setInt(2,user.getAge());
                ps.setInt(3,user.getId());
            }
        });

        return result;
    }

    public int deleteUser(int id) {
        int result = jdbcTemplate.update("delete from UserInfo where id=?",new Object[]{id},new int[]{Types.INTEGER});
        return result;
    }
}

View Code

 

6、Controller

图片 12图片 13

@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    private IUserBiz userBiz;
    @RequestMapping("/index")
    public ModelAndView index(){
        List<User> list =userBiz.listAllUser();
        return new ModelAndView("index");
    }

    @RequestMapping(value="/userJson",method = RequestMethod.GET)
    public ResponseEntity<JSONObject> getUserJson(@RequestParam("page")int pageIndex, @RequestParam("rows")int pageSize){

        JSONObject obj =new JSONObject();

        List<User> list =userBiz.listPagedUser(pageIndex,pageSize);
        int total=userBiz.getUserCount();
        obj.put("total",total);
        obj.put("rows",list);

        return new ResponseEntity<JSONObject>(obj, HttpStatus.OK);
    }

    @RequestMapping(value="/deleteUser",method = RequestMethod.POST)
    public ResponseEntity<JSONObject> deleteUser(@RequestParam("id")int id){
        JSONObject obj =new JSONObject();

        int result = userBiz.deleteUser(id);
        obj.put("returncode",result);
        obj.put("msg",result>0?"success":"error");

        return new ResponseEntity<JSONObject>(obj,HttpStatus.OK);
    }

    @RequestMapping(value="/saveUser",method = RequestMethod.POST)
    public ResponseEntity<JSONObject> saveUser(@RequestBody User user){
        JSONObject obj =new JSONObject();

        int result = userBiz.insertUser(user);
        obj.put("returncode",result);
        obj.put("msg",result>0?"success":"error");

        return new ResponseEntity<JSONObject>(obj,HttpStatus.OK);
    }

    @RequestMapping(value="/editUser",method = RequestMethod.POST)
    public ResponseEntity<JSONObject> updateUser(@RequestBody User user){
        JSONObject obj =new JSONObject();

        int result = userBiz.updateUser(user);
        obj.put("returncode",result);
        obj.put("msg",result>0?"success":"error");

        return new ResponseEntity<JSONObject>(obj,HttpStatus.OK);
    }
}

View Code

 

   dialog:成立并编写一条单一的多少

View Code

总结

   
 做那些demo的经过中,首先蒙受了SpringMVC中拜候静态的财富的,再不怕用ajax
post访谈央浼Controller参数的格式及语法难点,contentType参数很要紧,作者是通过把参数种类化成字符串,然后在Controller通过bean的秘技接受,首要注解ResponseBody。

 

   form:用于提交表单数据

 

   messager:展现一些操作音信

后台代码:

二、操作步骤

图片 14图片 15

 1.备选数据库并创立实例数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace EasyUIDemo.ashx
{
    /// <summary>
    /// RoleList 的摘要说明
    /// </summary>
    public class RoleList : IHttpHandler
    {


        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            String action = context.Request["action"];

            if (action.Equals("GetRoleList"))
            {
                DataTable dt = SqlHelper.ExecuteDt("select UserID,UserName,UserPassword,NickName,DeptID,Phone from tbUser");
                context.Response.Write(FormatToJson.ToJson(dt));

            }
            //添加
            else if (action.Equals("add"))
            {
                String UserName = context.Request["UserName"];
                String UserPassword = context.Request["UserPassword"];
                String NickName = context.Request["NickName"];
                String DeptID = context.Request["DeptID"];
                String Phone = context.Request["Phone"];



                String sql = "insert into tbUser(UserName,UserPassword,NickName,DeptID,Phone) values(@UserName,@UserPassword,@NickName,@DeptID,@Phone)";
                SqlParameter[] para = new SqlParameter[] { 
                                                           new SqlParameter("@UserName",UserName),
                                                            new SqlParameter("@UserPassword",UserPassword),
                                                             new SqlParameter("@NickName",NickName),
                                                              new SqlParameter("@DeptID",DeptID),
                                                            new SqlParameter("@Phone",Phone),
                                                           };
                int i = SqlHelper.ExecuteSql(sql, para);
                if (i > 0)
                {

                    context.Response.Write("ok");
                }
                else
                {
                    context.Response.Write("no");
                }

            }
            //编辑
            else if (action.Equals("edit"))
            {
                String UserName = context.Request["UserName"];
                String UserPassword = context.Request["UserPassword"];
                String NickName = context.Request["NickName"];
                String DeptID = context.Request["DeptID"];             
                String Phone = context.Request["Phone"];

                String UserID = context.Request["UserID"];

                String sql = "update tbUser set UserName=@UserName,UserPassword=@UserPassword,NickName=@NickName,DeptID=@DeptID,Phone=@Phone where UserID=@UserID";
                SqlParameter[] para = new SqlParameter[] { 
                                                             new SqlParameter("@UserName",UserName),
                                                             new SqlParameter("@UserPassword",UserPassword),
                                                             new SqlParameter("@NickName",NickName),
                                                             new SqlParameter("@DeptID",DeptID),
                                                             new SqlParameter("@Phone",Phone),
                                                             new SqlParameter("@UserID",UserID)
                                                           };
                int i = SqlHelper.ExecuteSql(sql, para);
                if (i > 0)
                {

                    context.Response.Write("ok");
                }
                else
                {
                    context.Response.Write("no");
                }

            }

            //查询
            else if (action.Equals("search"))
            {


                String UserID = context.Request["UserID"];

                DataTable dt = SqlHelper.ExecuteDt("select UserID,UserName,UserPassword,NickName,DeptID,Phone from tbUser where UserID=" + UserID);
                context.Response.Write(FormatToJson.ToJson(dt));

            }
            else if (action.Equals("deleteRole"))
            {
                String UserID = context.Request["id"];
                String sql = "delete  from tbUser where UserID='" + UserID+"'";
                if (SqlHelper.ExecuteSql(sql) > 0)
                {
                    context.Response.Write("ok");
                }
                else
                {
                    context.Response.Write("no");
                }

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 2.创立DataGrid来浮现客商音讯

View Code

  创造没有JavaScript代码的DataGrid

 

 1 <table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"
 2         url="get_users.php"
 3         toolbar="#toolbar"
 4         rownumbers="true" fitColumns="true" singleSelect="true">
 5     <thead>
 6         <tr>
 7             <th field="firstname" width="50">First Name</th>
 8             <th field="lastname" width="50">Last Name</th>
 9             <th field="phone" width="50">Phone</th>
10             <th field="email" width="50">Email</th>
11         </tr>
12     </thead>
13 </table>
14 <div id="toolbar">
15     <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
16     <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
17     <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
18 </div>

源码下载:

来得结果如图:

图片 16

 

DataGrid中的url属性中的get_user.php用来从服务器检索数据、

1 $rs = mysql_query('select * from users');
2 $result = array();
3 while($row = mysql_fetch_object($rs)){
4     array_push($result, $row);
5 }
6 
7 echo json_encode($result);

3.开立表单对话框

动用相同的对话框来创造或编辑顾客

 1 <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
 2         closed="true" buttons="#dlg-buttons">
 3     <div class="ftitle">User Information</div>
 4     <form id="fm" method="post">
 5         <div class="fitem">
 6             <label>First Name:</label>
 7             <input name="firstname" class="easyui-validatebox" required="true">
 8         </div>
 9         <div class="fitem">
10             <label>Last Name:</label>
11             <input name="lastname" class="easyui-validatebox" required="true">
12         </div>
13         <div class="fitem">
14             <label>Phone:</label>
15             <input name="phone">
16         </div>
17         <div class="fitem">
18             <label>Email:</label>
19             <input name="email" class="easyui-validatebox" validType="email">
20         </div>
21     </form>
22 </div>
23 <div id="dlg-buttons">
24     <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>
25     <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>
26 </div>

展现页面如图:

图片 17

4.贯彻创设和编辑顾客

当创设客户时,打开一个会话框并清空表单数据

1 function newUser(){
2     $('#dlg').dialog('open').dialog('setTitle','New User');
3     $('#fm').form('clear');
4     url = 'save_user.php';
5 }

当编辑客商时,展开叁个会话框并从datagrid选择的行中加载表单数据

1 var row = $('#dg').datagrid('getSelected');
2 if (row){
3     $('#dlg').dialog('open').dialog('setTitle','Edit User');
4     $('#fm').form('load',row);
5     url = 'update_user.php?id='+row.id;
6 }

url中存放着顾客数据表单回传的U传祺L地址

5.保存顾客数量

 1 function saveUser(){
 2     $('#fm').form('submit',{
 3         url: url,
 4         onSubmit: function(){
 5             return $(this).form('validate');
 6         },
 7         success: function(result){
 8             var result = eval('('+result+')');
 9             if (result.errorMsg){
10                 $.messager.show({
11                     title: 'Error',
12                     msg: result.errorMsg
13                 });
14             } else {
15                 $('#dlg').dialog('close');        // close the dialog
16                 $('#dg').datagrid('reload');    // reload the user data
17             }
18         }
19     });
20 }

交付表单从前,onSubmit函数将被调用,该函数用来验证表单字段值,当表单字段值提交成功,关闭对话框并再一次加载datagrid数据

6.删减叁个客商

 1 function destroyUser(){
 2     var row = $('#dg').datagrid('getSelected');
 3     if (row){
 4         $.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
 5             if (r){
 6                 $.post('destroy_user.php',{id:row.id},function(result){
 7                     if (result.success){
 8                         $('#dg').datagrid('reload');    // reload the user data
 9                     } else {
10                         $.messager.show({    // show error message
11                             title: 'Error',
12                             msg: result.errorMsg
13                         });
14                     }
15                 },'json');
16             }
17         });
18     }
19 }

图片 18

 

在剔除一行在此以前,大家将展现叁个确认对话框让客户决定是还是不是真正删除该行数据,当移除数据成功今后,调用reload方法刷新datagrid数据、

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图