基于easyui的 增 删 改 查

项目结构图


一:web.xml代码
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< web-app  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns = "http://java.sun.com/xml/ns/javaee"  xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  id = "WebApp_ID"  version = "2.5" >
   < display-name >elve</ display-name >
   < context-param >
     < param-name >contextConfigLocation</ param-name >
     < param-value >
             classpath:app-context.xml
     </ param-value >
   </ context-param >
   < context-param >
     < param-name >webAppRootKey</ param-name >
     < param-value >demo.root</ param-value >
   </ context-param >
   
   
   < filter >
     < filter-name >encodingFilter</ filter-name >
     < filter-class >
             org.springframework.web.filter.CharacterEncodingFilter
         </ filter-class >
     < init-param >
       < param-name >encoding</ param-name >
       < param-value >UTF-8</ param-value >
     </ init-param >
   </ filter >
   < filter-mapping >
     < filter-name >encodingFilter</ filter-name >
     < url-pattern >/*</ url-pattern >
   </ filter-mapping >
   < listener >
     < listener-class >
         org.springframework.web.context.ContextLoaderListener
     </ listener-class >
   </ listener >
   < listener >
     < listener-class >
         com.xs.demo.listener.SessionListener
     </ listener-class >
   </ listener >
   < servlet >
     < servlet-name >app</ servlet-name >
        < servlet-class >
         org.springframework.web.servlet.DispatcherServlet
     </ servlet-class >
     < init-param >
       < param-name >contextConfigLocation</ param-name >
       < param-value >classpath:app-servlet.xml</ param-value >
     </ init-param >
     < load-on-startup >2</ load-on-startup >
   </ servlet >
   < servlet-mapping >
     < servlet-name >app</ servlet-name >
     < url-pattern >/</ url-pattern >
   </ servlet-mapping >
   < session-config >
     < session-timeout >60</ session-timeout >
   </ session-config >
   < welcome-file-list >
     < welcome-file >index.jsp</ welcome-file >
     < welcome-file >index.html</ welcome-file >
   </ welcome-file-list >
   < error-page >
     < error-code >500</ error-code >
     < location >/system/500.jsp</ location >
   </ error-page >
   < error-page >
     < error-code >404</ error-code >
     < location >/system/404.jsp</ location >
   </ error-page >
   < error-page >
     < error-code >403</ error-code >
     < location >/system/403.jsp</ location >
   </ error-page >
</ web-app >

1.UserController代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package  com.xs.demo.controller;
 
import  java.net.URLEncoder;
import  java.util.HashMap;
import  java.util.Map;
 
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
 
import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.ServletRequestUtils;
import  org.springframework.web.bind.annotation.RequestMapping;
 
import  com.google.gson.Gson;
import  com.google.gson.GsonBuilder;
import  com.xs.demo.entity.Userinfo;
import  com.xs.demo.service.UserService;
import  com.xs.demo.util.StringUtil;
/**
  * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
  * @author
  * 类名称:UserController 
  * @date 2014-11-15 下午4:05:32 
  * 备注:
  */
@Controller
@RequestMapping (value= "/user" )
public  class  UserController {
     
     UserService userService;
     
     private  static  Log log = LogFactory.getLog(UserController. class );
     
     /**
      * index --list
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value= "/index" )
     public  String index(HttpServletRequest request,
             HttpServletResponse response) throws  Exception{
         return  "/views/user/index" ;
     }
     /**
      * list method
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value =  "/list" )
     public  String list(HttpServletRequest request,
             HttpServletResponse response)  throws  Exception{
         int  start = ServletRequestUtils.getIntParameter(request,  "page" 1 )- 1 ;
         int  size = ServletRequestUtils.getIntParameter(request,  "rows" 0 );
         String name = ServletRequestUtils.getStringParameter(request,  "name" , "" );
         String order = StringUtil.getOrderString(request);     //取得排序参数
         
         String result =  null ;
         try {
             result = userService.list(name,start, size, order);
         } catch  (Exception e) {
             if (log.isErrorEnabled()){
                 log.error( "查询列表失败" , e);
             }
             result =  "" ;
         }
         String sortName = ServletRequestUtils.getStringParameter(request,  "sort" "" );
         String sortOrder = ServletRequestUtils.getStringParameter(request,  "order" "" );
         Map<String, Object> searchMap =  new  HashMap<String,Object>();
         searchMap.put( "pageNumber" , start+ 1 );
         searchMap.put( "rows" , size);
         searchMap.put( "sortName" , sortName);
         searchMap.put( "sortOrder" , sortOrder);
         Gson gson =  new  GsonBuilder().setDateFormat( "yyyy-MM-dd" ).create();
         String s = gson.toJson(searchMap);
         s = URLEncoder.encode(s, "UTF-8" ); 
         
         StringUtil.writeToWeb(result,  "html" , response);
         return  null ;
     }
     /**
      * gotoAdd --page
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value= "/gotoAdd" )
     public  String gotoAdd(HttpServletRequest request,
             HttpServletResponse response)  throws  Exception{
         return  "views/user/add" ;
     }
     /**
      * add --method
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value= "/add" )
     public  String add(HttpServletRequest request,
             HttpServletResponse response) throws  Exception {
         String result =  null ;
         Userinfo userinfo = (Userinfo)StringUtil.requestToObject(request, Userinfo. class );
         Userinfo dbUserinfo =  userService.getUserByName(userinfo.getName());
         if (dbUserinfo!= null ){
             result =  "{\"success\":false,\"msg\":\"名称已存在!\"}" ;
             StringUtil.writeToWeb(result,  "html" , response);
             return  null ;
         }
         try {
             if (userinfo.getName().trim().length()< 0 ){
                 result =  "{\"success\":false,\"msg\":\"名称不能为空!\"}" ;
                 StringUtil.writeToWeb(result,  "html" , response);
                 return  null ;
             } else  if ( null  == userinfo.getAge()){
                 result =  "{\"success\":false,\"msg\":\"年龄参数有误!\"}" ;
                 StringUtil.writeToWeb(result,  "html" , response);
                 return  null ;
             } else {
                 result = userService.save(userinfo);
             }
         } catch (Exception e){
             if (log.isErrorEnabled()){
                 log.error( "新增失败" , e);
             }
             result =  "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}" ;
         }
         StringUtil.writeToWeb(result,  "html" , response);
         return  null ;
     }
     /**
      * gotoModify --page
      * @param request
      * @param response
      * @return
      */
     @RequestMapping (value= "/gotoModify" )
     public  String gotoModify(HttpServletRequest request,
             HttpServletResponse response) throws  Exception {
         Integer id = ServletRequestUtils.getIntParameter(request, "id" );
         Userinfo userinfo = userService.get(Userinfo. class ,id);
         request.setAttribute( "userinfo" , userinfo);
             return  "views/user/modify" ;
     }
     /**
      * modify --method
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value= "/modify" )
     public  String modify(HttpServletRequest request,
             HttpServletResponse response)  throws  Exception {
         Integer id = ServletRequestUtils.getIntParameter(request,  "id" );
         Userinfo dbUserinfo = userService.get(Userinfo. class , id);
         Userinfo userinfo = (Userinfo) StringUtil.requestToObject(request, Userinfo. class );
         String result;
         if (!dbUserinfo.getName().equals(userinfo.getName())){
             Userinfo hasUserinfo = userService.getUserByName(userinfo.getName());
             if (hasUserinfo!= null ){
                 result =  "{\"success\":false,\"msg\":\"角色名称已存在!\"}" ;
                 StringUtil.writeToWeb(result,  "html" , response);
                 return  null ;
             }
         }
         try {
             result = userService.update(request,userinfo, id);
         } catch  (Exception e ){
             if (log.isErrorEnabled()){
                 log.error( "修改失败" , e);
             }
             result =  "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}" ;
         }
         StringUtil.writeToWeb(result,  "html" , response);
         return  null ;
     }
     /**
      * delete --method
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
     @RequestMapping (value =  "/delete" )
     public  String delete(HttpServletRequest request,
             HttpServletResponse response)  throws  Exception{
         Integer id = ServletRequestUtils.getIntParameter(request,  "id" );
         
         try {
             if ( null  != id){
                 userService.delete(id);
             }
             String result =  "{\"success\":true,\"msg\":\"删除成功\"}" ;
             StringUtil.writeToWeb(result,  "html" , response);
             return  null ;
         catch  (Exception e) {
             if (log.isErrorEnabled()){
                 log.error( "删除失败" , e);
             }
             String result =  "{\"success\":false,\"msg\":\"删除失败,请稍候再试!\"}" ;
             StringUtil.writeToWeb(result,  "html" , response);
             return  null ;
         }
     }
     public  UserService getUserService() {
         return  userService;
     }
 
     public  void  setUserService(UserService userService) {
         this .userService = userService;
     }
     
}

2.UserService代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package  com.xs.demo.service;
 
import  java.io.Serializable;
import  java.util.Date;
import  java.util.HashMap;
import  java.util.List;
import  java.util.Map;
 
import  javax.servlet.http.HttpServletRequest;
 
 
 
 
 
import  com.google.gson.Gson;
import  com.google.gson.GsonBuilder;
import  com.xs.demo.dao.UserDao;
import  com.xs.demo.entity.Userinfo;
import  com.xs.demo.util.StringUtil;
/**
  *  SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
  * @author
  * 类名称:UserService 
  * @date 2014-11-15 下午4:14:37 
  * 备注:
  */
public  class  UserService  extends  BaseService {
     UserDao userDao;
     /**
      * list
      * @param name
      * @param start
      * @param size
      * @param order
      * @return
      */
     public  String list(String name, int  start,  int  size, String order){
         List<Map<String,Object>> list =userDao.list(name,start, size, order); 
         int  count = count(name,start, size, order);
         
         Map<String,Object> map =  new  HashMap<String, Object>();
         map.put( "total" , count);
         map.put( "rows" , list);
         
         Gson gson =  new  GsonBuilder().setDateFormat( "yyyy-MM-dd HH:mm:ss" ).create();
         String s = gson.toJson(map);
         return  s;
     }
     /**
      * save
      * @param userinfo
      * @return
      */
     public  String save(Userinfo userinfo) {
         String result =  null ;
         Date date =  new  Date();
         userinfo.setBirthday(date);
         userinfo.setPassword( "888888" );
         super .save(userinfo);
         result =  "{\"success\":true,\"msg\":\"新增角色成功\"}" ;
         return  result ;
     }
     /**
      * count
      * @param name
      * @param start
      * @param size
      * @param order
      * @return
      */
     public  int  count(String name, int  start,  int  size, String order){
         return  userDao.count(name,start, size, order);
     }
     /**
      * getuserbyname
      * @param name
      * @return
      */
     public  Userinfo getUserByName(String name) {
         return  userDao.getUserByName(name);
     }
     /**
      * update
      * @param request
      * @param userinfo
      * @param id
      * @return
      */
     public  String update(HttpServletRequest request, Userinfo userinfo,
             Integer id) {
         Userinfo userinfoOld =  super .get(Userinfo. class , id);
         if ( null  != userinfo){
             StringUtil.requestToObject(request, userinfoOld);
         }
         super .update(userinfoOld);
         String result =  "{\"success\":true,\"msg\":\"更新成功!\"}" ;
         return  result;
     }
     /**
      * delete
      * @param id
      */
     public  void  delete(Serializable id){
         userDao.delete(Userinfo. class ,id);
     }
     
     /*------------------*/
     public  UserDao getUserDao() {
         return  userDao;
     }
     public  void  setUserDao(UserDao userDao) {
         this .userDao = userDao;
     }    
}


3.UserDao

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package  com.xs.demo.dao;
 
import  java.util.ArrayList;
import  java.util.List;
import  java.util.Map;
 
 
import  com.xs.demo.entity.Userinfo;
/**
  * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
  * @author 
  * 类名称:UserDao 
  * @date 2014-11-15 下午4:34:51 
  * 备注:
  */
public  class  UserDao  extends  BaseDao{
 
     public  List<Map<String, Object>> list(String name, int  start,  int  size,
             String order) {
         List<Object> param =  new  ArrayList<Object>();
         String sql =  "select u.* from userinfo u where 1=1 " ;
         if ( null  != name && name.trim().length() >  0 ){
             sql +=  " and u.name like ? " ;
             param.add( "%" +name+ "%" );
         }
         if ( null  == order || order.length() ==  0 ){
             order =  " birthday asc" ;
         }
         return  super .listByNative(sql, param.toArray(), start, size, order);
     }
 
     public  int  count(String name, int  start,  int  size,
             String order) {
         List<Object> param =  new  ArrayList<Object>();
         String sql =  "select count(*) from userinfo u where 1=1 " ;
         if ( null  != name && name.trim().length() >  0 ){
             sql +=  " and u.name like ? " ;
             param.add( "%" +name+ "%" );
         }
         return  super .countByNative(sql, param.toArray());
     }
 
     @SuppressWarnings ( "unchecked" )
     public  Userinfo getUserByName(String name) {
         String hql= "select u from Userinfo u where u.name=? " ;
         List<Userinfo> list= super .list(hql,  new  Object[]{name});
         if (list!= null &&list.size()> 0 ){
             return  list.get( 0 );
         } else {
             return  null ;
         }
     }
 
}

4.add.jsp

<! DOCTYPE  html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8" %>
< html  xmlns = "http://www.w3.org/1999/xhtml" >
< head >
<%@ include file="/common/meta.jsp"%>
< meta  http-equiv = "Content-Type"  content = "text/html; charset=utf-8"  />
< title >SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</ title >
< script  type = "text/javascript" >
     function doCancel(){
         document.location.href="${ctx }/user/index";
     }
     
     $(function(){
         $('#form1').form({
             onSubmit: function(){
                 var v = $(this).form('validate');
                     if(v){
                         $("#doSubmit").unbind('click');
                     }
                     return v;
             },
             success:function(data){
                 data = eval('(' + data + ')');
                 if(data.success == true){
                     document.location.href="${ctx }/user/index";
                 }else {
                         $("#doSubmit").bind("click",function(){
                        $('#form1').submit();
                     });
                     alert(data.msg);
                 }
             }
         });
         $("#doSubmit").click(function() {
             $('#form1').submit();
             return false;
         });
     });
</ script >
</ head >
< body >
< div  class = "tables_title" >Add New UserInfo</ div >
< form  action = "${ctx }/user/add "  id = "form1"  method = "post" >
     < div  class = "dengji_table" >
         < div  class = "basic_table" >
             < div  class = "clospan" >
                 < p  class = "basic_name" >名称</ p >
                 < p >
                 < input  name = "name"   id = "name"  type = "text"  class = "easyui-validatebox"   data-options = "required:true"  placeholder = "输入中文" />
                 </ p >
              </ div >
          </ div >
          < div  class = "basic_table" >
             < div  class = "clospan" >
                 < p  class = "basic_name"  style = " border-right:none;" >年龄</ p >
                 < p >
                 < input  name = "age"   id = "age"  type = "number"   min = "18"  max = "99"  class = "easyui-validatebox"   data-options = "required:true"  placeholder = "年龄不得小于18" />
                 </ p >
         </ div >
         </ div >
         < div  class = "basic_table" >
           < div  class = "clospan" >
              < p  class = "basic_name"  style = " border-right:none;" >地址</ p >
              < p > < input  name = "address"   id = "address"  type = "text"   class = "easyui-validatebox"   data-options = "required:true"  placeholder = "市区名" />
                 </ p >
         </ div >
         </ div >
            < div  class = "clospan_func" >
              < div  class = "btns" >
               < a  href = "javascript:void(0);"  id = "doSubmit"  class = "blank_btn" >保存</ a >
               < a  href = "javascript:void(0);"  onclick = "doCancel();"  class = "blank_btn" >返回</ a >
              </ div >
             </ div >
         </ div >
       </ form >
</ body >
</ html >

5.index.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<! DOCTYPE  html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html  xmlns = "http://www.w3.org/1999/xhtml" >
< head >
<%@ include file="/common/meta.jsp"%>
< meta  http-equiv = "Content-Type"  content = "text/html; charset=utf-8"  />
< title >SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</ title >
< script  type = "text/javascript" >
     var searchString;
 
     function resizeDg(){
         $('#dg').datagrid("resize", { width: $(window).width() * 0.4});
     }
     
     function getCookie(c_name){
          if (document.cookie.length>0){
           c_start=document.cookie.indexOf(c_name + "=");
           if (c_start!=-1){ 
             c_start=c_start + c_name.length+1;
             c_end=document.cookie.indexOf(";",c_start);
             if (c_end==-1) {
                 c_end=document.cookie.length;
             }
             return document.cookie.substring(c_start,c_end);
           
           }
         return "";
     }
     
     var pageSize = 20;
     var pageNumber = 1;
     var sortName = '';
     var sortOrder = '';
     function initDate(){
         var s = getCookie("role");
         s = decodeURIComponent(s);
         if(s != null && s != ""){
             searchMap = eval('(' + s + ')');
             pageSize = searchMap.rows;
             if(pageSize == null || pageSize == ""){
                 pageSize = 20;
             }
             pageNumber = searchMap.pageNumber;
             sortName = searchMap.sortName;
             sortOrder = searchMap.sortOrder;
             $("#name").val(searchMap.name );
         }
     }
     
     $(function(){
          $("#doSearch").click(function(){
             doSearch();
         });
         initDate();
         var name=$("#name").val();
         $('#dg').datagrid({
             url:"${ctx }/user/list",
             pagination:true,
             singleSelect:true,
             pageSize:pageSize,
             pageNumber:pageNumber,
             sortOrder:sortOrder,
             sortName:sortName,
             queryParams:{  
                 name:name,
             },
             width:800,
                columns:[[
                    {field:'name',title:'名称', width:100, align:"center",sortable:true},
                    {field:'age',title:'年龄', width:50, align:"center",sortable:true},
                    {field:'address',title:'地址', width:50, align:"center",sortable:true},
                    {field:'operation',title:'操作', width:340, align:"center", sortable:false,
                        formatter:function(value,row,index){
                            var s ="";
                         s+="< a  href=\"javascript:void(0)\">< span  onclick=\"javaScript:gotoModify('"+row.id+"');\">修改</ span ></ a >";
                            s += "|";
                         s+="< a  href=\"javascript:void(0)\">< span  onclick=\"javaScript:gotoDel('"+row.id+"');\">删除</ span >&nbsp;&nbsp;</ a >";
                         return s;
                        }
                    }
                ]]
         });
          var p = $('#dg').datagrid('getPager');    
          $(p).pagination({    
               pageList: [10,20,50,100]
           });  
         
         $("#doSearch").click(function(){
             doSearch();
         });
     });
     
     
     function gotoAdd(){
         var url = '${ctx }/user/gotoAdd';
         window.location.href=url;
     }
     function gotoModify(id){
         var url = '${ctx}/user/gotoModify?id='+id;
         window.location.href=url;
     }
     function gotoDel(id){
         if(!confirm('确定删除所选记录?')){
             return;
         }
         var url = '${ctx}/user/delete?id='+id;
         $.ajax({
             type : 'post',
             url : url,
             dataType: "json",
                 success:function(data){
                     if(data.success == true){
                         doSearch();
                     }else{
                         alert(data.msg);
                     }
                 }
             });
     }
         
     function doSearch(){
         var name=$("#name").val();
         /* var schoolId=$("#schoolId").val(); */
         $("#dg").datagrid('load',{  
             name:name
         }); //重新载入 
     }
         
</ script >
</ head >
< body  onload = "resizeDg();"  onresize = "resizeDg();"  >
< div  class = "neirong" >
< div  class = "add-content"  style = "margin-top:0" >
     < div  class = "xinxi2" >
            < div  class = "search_box" >
            < p >名称: < input  name = "name"  id = "name"  type = "text"  /></ p >
            < a  href = "javascript:void(0);"  id = "doSearch"  class = "blank_btn" >查询</ a ></ div >
            < div  class = "btn_div" >
            < a  href = "javascript:void(0);"  onclick = "gotoAdd();"  id = "xtsz_rygl_jsgl_add"  class = "blank_btn" >新增</ a >
            </ div >
        </ div >
     < div  class = "contant_list"  >
         <!-- c_top start-->
         < table   width = "100%" >
             < tr >
                 < td >
                     < table  id = "dg" ></ table >
                 </ td >
             </ tr >
         </ table >
     </ div >
   </ div >
</ div >
</ body >
</ html >

6.modfiy.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<! DOCTYPE  html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8" %>
< html  xmlns = "http://www.w3.org/1999/xhtml" >
< head >
<%@ include file="/common/meta.jsp"%>
< meta  http-equiv = "Content-Type"  content = "text/html; charset=utf-8"  />
< title >修改用户信息</ title >
< script  type = "text/javascript" >
 
     function doCancel(){
         document.location.href="${ctx }/user/index";
     }
     
     $(function(){
         $('#form1').form({
             onSubmit: function(){
                 var v = $(this).form('validate');
                     if(v){
                         $("#doSubmit").unbind('click');
                     }
                     return v;
             },
             success:function(data){
                 data = eval('(' + data + ')');
                 if(data.success == true){
                     document.location.href="${ctx }/user/index";
                 }else {
                         $("#doSubmit").bind("click",function(){
                        $('#form1').submit();
                     });
                     alert(data.msg);
                 }
             }
         });
         $("#doSubmit").click(function() {
             $('#form1').submit();
             return false;
         });
 
     });
</ script >
</ head >
< body >
< div  class = "tables_title" >修改用户</ div >
< form  action = "${ctx }/user/modify"  id = "form1"  method = "post" >
  < input  type = "hidden"  name = "id"  value = "${userinfo.id }" ></ input >
< div  class = "dengji_table" >
         < div  class = "basic_table" >
             < div  class = "clospan" >
                 < p  class = "basic_name" >名称</ p >
                 < p >
                 < input  name = "name"   id = "name"  type = "text"  class = "easyui-validatebox"   data-options = "required:true"  value = "${userinfo.name}" />
                 </ p >
              </ div >
          </ div >
          < div  class = "basic_table" >
             < div  class = "clospan" >
                 < p  class = "basic_name"  style = " border-right:none;" >年龄</ p >
                 < p >
                 < input  name = "age"   id = "age"  type = "number"   min = "18"  max = "99"  class = "easyui-validatebox"   data-options = "required:true"  value = "${userinfo.age}" />
                 </ p >
         </ div >
         </ div >
         < div  class = "basic_table" >
           < div  class = "clospan" >
                 < p  class = "basic_name"  style = " border-right:none;" >地址</ p >
                 < p >
                 < input  name = "address"   id = "address"  type = "text"   class = "easyui-validatebox"   data-options = "required:true"  value = "${userinfo.address}" />
                 </ p >
         </ div >
         </ div >
              < div  class = "clospan_func" >
                 < div  class = "btns" >
                     < a  href = "javascript:void(0);"  id = "doSubmit"  class = "blank_btn" >保存</ a >
                     < a  href = "javascript:void(0);"  onclick = "doCancel();"  class = "blank_btn" >返回</ a >
                 </ div >
             </ div >
         </ div >
       </ form >
</ body >
</ html >

7.app-aop.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans 
     xmlns = "http://www.springframework.org/schema/beans" 
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop = "http://www.springframework.org/schema/aop"
     xmlns:jee = "http://www.springframework.org/schema/jee" 
     xmlns:tx = "http://www.springframework.org/schema/tx"
     xmlns:context = "http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
         http://www.springframework.org/schema/tx 
         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
         http://www.springframework.org/schema/jee 
         http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context-3.2.xsd"
     default-autowire = "byName" >
     
     
     < aop:config >
         < aop:pointcut  id = "testPointcut"  expression = "execution(* cn.com.elve.live..service..*.*(..))"  />
     </ aop:config >
     <!-- 普通的AOP,如果想得到被代理的方法参数,那么就必须在配置里提前写好,这样有非常大的局限性 -->
     < aop:config >
         < aop:aspect  ref = "testSchemaAop" >
             < aop:before  method = "before"  pointcut-ref = "testPointcut" />
             < aop:after-returning  method = "afterReturning"  pointcut-ref = "testPointcut"  returning = "object" />
             < aop:after-throwing  method = "afterThrowing"  pointcut-ref = "testPointcut"  throwing = "object" />
             < aop:after  method = "after"  pointcut-ref = "testPointcut" />
         </ aop:aspect >
     </ aop:config >
     
     <!-- 基于advisor的代理,代理类需要实现spring提供的接口,然后就可以用到强大的功能了。 -->
     < aop:config >
         < aop:advisor  pointcut-ref = "testPointcut"  advice-ref = "afterReturn"  />
     </ aop:config >
     
     
     
     <!-- 需要由spring注入的bean定义 -->
     < bean  id = "afterReturn"  class = "com.xs.demo.aop.AfterReturn" />
     < bean  id = "afterThrow"  class = "com.xs.demo.aop.AfterThrow" />
     < bean  id = "before"  class = "com.xs.demo.aop.Before" />
     < bean  id = "testSchemaAop"  class = "com.xs.demo.aop.TestSchemaAop" />
     
     
     
</ beans >

8.app-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans 
     xmlns = "http://www.springframework.org/schema/beans" 
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop = "http://www.springframework.org/schema/aop"
     xmlns:jee = "http://www.springframework.org/schema/jee" 
     xmlns:tx = "http://www.springframework.org/schema/tx"
     xmlns:context = "http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
         http://www.springframework.org/schema/tx 
         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
         http://www.springframework.org/schema/jee 
         http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context-3.2.xsd"
     default-autowire = "byName" >
     <!-- 使用annotation 自动注册bean -->
     < context:annotation-config />
     < context:component-scan  base-package = "com.xs.demo" >
         < context:include-filter  type = "regex"  expression = ".*Service" />
         < context:include-filter  type = "regex"  expression = ".*Dao" />
         < context:include-filter  type = "regex"  expression = ".*Job" />
     </ context:component-scan >
     
     
     < import  resource = "classpath:/app-db.xml" />
     
     <!-- 配置文件读取 -->
     < bean  class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
         < property  name = "locations" >
             < list >
                 < value >classpath:/jdbc.properties</ value >
                 < value >classpath:/hibernate.properties</ value >
                 < value >classpath:/log4j.properties</ value >
             </ list >
         </ property >
     </ bean >      
     
     <!-- 开启AOP监听 只对当前配置文件有效 -->
     < aop:aspectj-autoproxy  expose-proxy = "true" />
     
     <!-- 开启注解事务 只对当前配置文件有效 -->
       < tx:annotation-driven  transaction-manager = "txManager" />
 
     < bean  id = "txManager"  class = "org.springframework.orm.hibernate4.HibernateTransactionManager" >
         < property  name = "sessionFactory"  ref = "sessionFactory" />
     </ bean >
 
     < tx:advice  id = "txAdvice"  transaction-manager = "txManager" >
         < tx:attributes >
             < tx:method  name = "save*"  propagation = "REQUIRED"  />
             < tx:method  name = "add*"  propagation = "REQUIRED"  />
             < tx:method  name = "create*"  propagation = "REQUIRED"  />
             < tx:method  name = "insert*"  propagation = "REQUIRED"  />
             < tx:method  name = "update*"  propagation = "REQUIRED"  />
             < tx:method  name = "modify*"  propagation = "REQUIRED"  />
             < tx:method  name = "upload*"  propagation = "REQUIRED"  />
             < tx:method  name = "merge*"  propagation = "REQUIRED"  />
             < tx:method  name = "del*"  propagation = "REQUIRED"  />
             < tx:method  name = "remove*"  propagation = "REQUIRED"  />
             < tx:method  name = "move*"  propagation = "REQUIRED"  />
             < tx:method  name = "change*"  propagation = "REQUIRED"  />
             < tx:method  name = "put*"  propagation = "REQUIRED"  />
             < tx:method  name = "use*"  propagation = "REQUIRED" />
             < tx:method  name = "log*"  propagation = "REQUIRED" />
             < tx:method  name = "sh*"  propagation = "REQUIRED" />
             < tx:method  name = "bh*"  propagation = "REQUIRED" />
             < tx:method  name = "sf*"  propagation = "REQUIRED" />
             < tx:method  name = "bj*"  propagation = "REQUIRED" />
             < tx:method  name = "tf*"  propagation = "REQUIRED" />
             < tx:method  name = "mobileLogin"  propagation = "REQUIRED" />
             < tx:method  name = "register*"  propagation = "REQUIRED" />
             < tx:method  name = "goto*"  propagation = "REQUIRED" />
             < tx:method  name = "active*"  propagation = "REQUIRED" />
             < tx:method  name = "send*"  propagation = "REQUIRED" />
             < tx:method  name = "handel*"  propagation = "REQUIRED" />
             < tx:method  name = "attendance*"  propagation = "REQUIRED" />
             < tx:method  name = "batch"  propagation = "REQUIRED" />
             <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
             < tx:method  name = "get*"  propagation = "REQUIRED"  read-only = "true"  />
             < tx:method  name = "count*"  propagation = "REQUIRED"  read-only = "true"  />
             < tx:method  name = "find*"  propagation = "REQUIRED"  read-only = "true"  />
             < tx:method  name = "list*"  propagation = "REQUIRED"  read-only = "true"  />
             < tx:method  name = "*"  read-only = "true"  />
         </ tx:attributes >
     </ tx:advice >
     < aop:config  expose-proxy = "true" >
         <!-- 只对业务逻辑层实施事务 -->
         < aop:pointcut  id = "txPointcut"  expression = "execution(* com.xs.demo..service..*.*(..))"  />
         < aop:advisor  advice-ref = "txAdvice"  pointcut-ref = "txPointcut" />
     </ aop:config >
     
     <!-- 自动扫描测试用service -->
<!--     <context:component-scan base-package="test.service"></context:component-scan> -->
     
     
     <!--    javaMailSender 
     <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl" >
         <property name="host" value="smtp.qq.com"/>
         <property name="port" value="465"/>
         <property name="username" value="elve@elve.cn"/>
         <property name="password" value="654123.huo"/>
         <property name="javaMailProperties">
             <props> 
                 <prop key="mail.smtp.auth">true</prop> 
                 <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
             </props> 
         </property> 
     </bean> -->     
         
</ beans >

9.app-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<? xml  version = "1.0"  encoding = "UTF-8" ?>
 
 
<!-- 配置urlMapping -->
< beans 
     xmlns = "http://www.springframework.org/schema/beans" 
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop = "http://www.springframework.org/schema/aop"
     xmlns:jee = "http://www.springframework.org/schema/jee" 
     xmlns:tx = "http://www.springframework.org/schema/tx"
     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-3.2.xsd 
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
         http://www.springframework.org/schema/tx 
         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
         http://www.springframework.org/schema/jee 
         http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context-3.2.xsd"
     default-autowire = "byName" >
     <!-- 启用基于注解的处理器映射,添加拦截器,类级别的处理器映射 -->
     < bean  class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >
         < property  name = "interceptors" >
             < list >
                 < bean  class = "org.springframework.web.servlet.i18n.LocaleChangeInterceptor"  />  
             </ list >
         </ property >
     </ bean >
     
     <!-- 设置自动扫描的controller类的路径,可以写多个 -->
     <!-- 例<context:component-scan base-package="cn.com.elve.live.controller,cn.com.elve.live.xxx"/> -->
     < context:component-scan  base-package = "com.xs.demo.controller" />
     <!-- 
     配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射,
     有人说该bean要放在context:component-scan前面,要不然不起作用,但我试的放后面也可以啊。
     -->
     < bean  class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
         < property  name = "cacheSeconds"  value = "0"  />
     </ bean >
     
     <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
     < mvc:resources  mapping = "/images/**"  location = "/images/" />
     < mvc:resources  mapping = "/js/**"  location = "/js/" />
     < mvc:resources  mapping = "/css/**"  location = "/css/" />
     < mvc:resources  mapping = "/swf/**"  location = "/swf/" />
     < mvc:resources  mapping = "/file/**"  location = "/file/" />
     < mvc:resources  mapping = "/FusionCharts/**"  location = "/FusionCharts/" />
     
     <!-- viewResolver 视图解析器,将视图名(ModelAndView中的view)解析成URL-->
     < bean  id = "viewResolver"
         class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
         < property  name = "suffix"  value = ".jsp"  />
         < property  name = "prefix"  value = "/WEB-INF/" />
         < property  name = "order"  value = "20" ></ property >
         < property  name = "viewClass"
             value = "org.springframework.web.servlet.view.InternalResourceView"  />
     </ bean >
     
      <!-- 针对freemarker的视图配置 -->
     < bean  id = "freeMarkerViewResolver"  class = "org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" >
         < property  name = "suffix"  value = ".ftl"  />
         < property  name = "order"  value = "5" ></ property >     <!--resolver排序,本resolver会早于viewResolver-->
         < property  name = "viewClass"  value = "org.springframework.web.servlet.view.freemarker.FreeMarkerView" ></ property >
         < property  name = "contentType"  value = "text/html;charset=UTF-8" ></ property >
         < property  name = "requestContextAttribute"  value = "request"  />
         < property  name = "exposeSpringMacroHelpers"  value = "true"  />
         < property  name = "exposeRequestAttributes"  value = "true"  />
         < property  name = "exposeSessionAttributes"  value = "true"  />
     </ bean >
     
     < bean  id = "freeMarkerConfigurer"  class = "org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
         < property  name = "templateLoaderPath"  value = "/WEB-INF/"  />
         < property  name = "freemarkerSettings" >
             < props >
                 < prop  key = "template_update_delay" >0</ prop >
                 < prop  key = "default_encoding" >UTF-8</ prop >
                 < prop  key = "number_format" >0.##########</ prop >
                 < prop  key = "datetime_format" >yyyy-MM-dd HH:mm:ss</ prop >
                 < prop  key = "classic_compatible" >true</ prop >
                 < prop  key = "template_exception_handler" >ignore</ prop >
             </ props >
         </ property >
     </ bean >
     
     
     <!--multipartResolver 支持分段文件上传 使用时form需要加上enctype="multipart/form-data"属性,且form的method设置为POST-->
     < bean  id = "multipartResolver"
         class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" >
         < property  name = "maxUploadSize"  value = "500400000"  />
         < property  name = "maxInMemorySize"  value = "4096"  />
         < property  name = "defaultEncoding"  value = "UTF-8" />
     </ bean >
     
     <!-- 国际化配置 -->  
     < bean  id = "localeResolver"  class = "org.springframework.web.servlet.i18n.CookieLocaleResolver"  >
         < property  name = "cookieName"  value = "clientlanguage" />
         < property  name = "cookieMaxAge"  value = "94608000" />
     </ bean >  
     
</ beans >

 使用的SpringMVC HandlerInterceptor验证是否登陆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package  com.xs.demo.inteceptor;
 
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
 
import  org.springframework.web.servlet.HandlerInterceptor;
import  org.springframework.web.servlet.ModelAndView;
 
 
public  class  Test  implements  HandlerInterceptor{
 
     @Override
     public  void  afterCompletion(HttpServletRequest arg0,
             HttpServletResponse arg1, Object arg2, Exception arg3)
             throws  Exception {
         System.out.println( "最后执行" );
     }
     @Override
     public  void  postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
             Object arg2, ModelAndView arg3)  throws  Exception {
         System.out.println( "第二步执行" );
     }
     @Override
     public  boolean  preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
             Object arg2)  throws  Exception {
         System.out.println( "主要的业务逻辑" );
         return  false ;
     }
 
}

代码很简单。判断session是否为空。且判断用户请求的url

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public  boolean  preHandle(HttpServletRequest request, HttpServletResponse response,
             Object handler)  throws  Exception {
         System.out.println( "第一步" );
         String path = request.getServletPath();
         if (path.startsWith( "/user/" )){
             Login userinfo = (Login) request.getSession().getAttribute(Constants.LOGIN_INFO);
             if ( null  == userinfo && !path.startsWith( "/user/gotoAdd/" )){
                 response.sendRedirect(request.getContextPath()+ "/system/login.jsp" );
                 return  false ;
             } else {
                 System.out.println( "else" );
                 return  true ;
             }
         }
         return  true ;
     }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyUI 是一个基于 jQuery 的 UI 库,可以快速地构建出美观的 web 应用程序。对于账户的功能,可以结合 EasyUI 提供的表格、表单、对话框等组件来实现。 以下是一个简单的账户管理示例: HTML: ```html <!-- 显示账户列表的表格 --> <table id="accountTable" class="easyui-datagrid" style="width:100%;height:400px" url="getAccounts.php" toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="id" width="50" sortable="true">ID</th> <th field="name" width="100" sortable="true">姓名</th> <th field="email" width="150" sortable="true">邮箱</th> <th field="phone" width="100" sortable="true">电话</th> </tr> </thead> </table> <!-- 工具栏,包含新、编辑、除按钮 --> <div id="toolbar"> <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newAccount()">新</a> <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editAccount()">编辑</a> <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyAccount()">除</a> </div> <!-- 新/编辑账户的对话框 --> <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px" closed="true" buttons="#dlg-buttons"> <div class="ftitle">账户信息</div> <form id="fm" method="post" novalidate> <div class="fitem"> <label>姓名:</label> <input name="name" class="easyui-textbox" required="true"> </div> <div class="fitem"> <label>邮箱:</label> <input name="email" class="easyui-textbox" validType="email"> </div> <div class="fitem"> <label>电话:</label> <input name="phone" class="easyui-textbox"> </div> </form> </div> <!-- 对话框底部的按钮 --> <div id="dlg-buttons"> <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveAccount()" style="width:90px">保存</a> <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#dlg').dialog('close')" style="width:90px">取消</a> </div> ``` JavaScript: ```javascript // 弹出新账户对话框 function newAccount() { $('#dlg').dialog('open').dialog('setTitle', '新账户'); $('#fm').form('clear'); } // 弹出编辑账户对话框 function editAccount() { var row = $('#accountTable').datagrid('getSelected'); if (row) { $('#dlg').dialog('open').dialog('setTitle', '编辑账户'); $('#fm').form('load', row); } } // 保存新/编辑的账户信息 function saveAccount() { $('#fm').form('submit', { url: 'saveAccount.php', onSubmit: function () { return $(this).form('validate'); }, success: function (result) { var result = eval('(' + result + ')'); if (result.success) { $('#dlg').dialog('close'); // 关闭对话框 $('#accountTable').datagrid('reload'); // 刷新表格 } else { $.messager.show({ title: 'Error', msg: result.msg }); } } }); } // 除选中的账户 function destroyAccount() { var row = $('#accountTable').datagrid('getSelected'); if (row) { $.messager.confirm('Confirm', '确定要除此账户吗?', function (r) { if (r) { $.post('destroyAccount.php', {id: row.id}, function (result) { if (result.success) { $('#accountTable').datagrid('reload'); // 刷新表格 } else { $.messager.show({ title: 'Error', msg: result.msg }); } }, 'json'); } }); } } ``` PHP: ```php <?php // getAccounts.php:获取账户列表 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $page = isset($_POST['page']) ? intval($_POST['page']) : 1; $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; $offset = ($page - 1) * $rows; $result = array(); $result['total'] = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM accounts")); $sql = "SELECT * FROM accounts LIMIT $offset,$rows"; $rs = mysqli_query($conn, $sql); $rows = array(); while ($row = mysqli_fetch_assoc($rs)) { $rows[] = $row; } $result['rows'] = $rows; mysqli_close($conn); echo json_encode($result); ?> <?php // saveAccount.php:保存新/编辑的账户信息 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $id = isset($_POST['id']) ? intval($_POST['id']) : 0; $name = isset($_POST['name']) ? mysqli_real_escape_string($conn, $_POST['name']) : ''; $email = isset($_POST['email']) ? mysqli_real_escape_string($conn, $_POST['email']) : ''; $phone = isset($_POST['phone']) ? mysqli_real_escape_string($conn, $_POST['phone']) : ''; if ($id > 0) { $sql = "UPDATE accounts SET name='$name',email='$email',phone='$phone' WHERE id=$id"; } else { $sql = "INSERT INTO accounts(name,email,phone) VALUES ('$name','$email','$phone')"; } if (mysqli_query($conn, $sql)) { $result = array('success' => true); } else { $result = array('success' => false, 'msg' => '保存失败:' . mysqli_error($conn)); } mysqli_close($conn); echo json_encode($result); ?> <?php // destroyAccount.php:除指定账户 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $id = isset($_POST['id']) ? intval($_POST['id']) : 0; if ($id > 0) { $sql = "DELETE FROM accounts WHERE id=$id"; if (mysqli_query($conn, $sql)) { $result = array('success' => true); } else { $result = array('success' => false, 'msg' => '除失败:' . mysqli_error($conn)); } } else { $result = array('success' => false, 'msg' => '无效的账户ID'); } mysqli_close($conn); echo json_encode($result); ?> ``` 这个示例中,使用了 EasyUI 提供的 `datagrid` 组件来显示账户列表,通过 `url` 属性指定了获取数据的 PHP 文件。在工具栏中,添加了新、编辑和除按钮,分别对应三个 JavaScript 函数 `newAccount()`、`editAccount()` 和 `destroyAccount()`。新和编辑时,会弹出一个对话框,使用 `form` 组件来输入账户信息,并通过 `submit` 方法提交表单数据到 `saveAccount.php` 文件进行保存。其中,提交表单数据时,使用了 `onSubmit` 属性来验证表单数据的有效性,`success` 回调函数中判断保存结果是否成功,并刷新账户列表。除时,会弹出一个确认框,确认除后,通过 `post` 方法将账户 ID 提交到 `destroyAccount.php` 文件进行除操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值