目錄結構
表結構
- CREATE TABLE `user` (
- `id` int(10) NOT NULL auto_increment,
- `username` varchar(50) default NULL,
- `password` varchar(50) default NULL,
- `sex` varchar(10) default NULL,
- `age` int(10) default NULL,
- `birthday` varchar(50) default NULL,
- `city` int(10) default NULL,
- `salary` varchar(50) default NULL,
- `starttime` varchar(100) default NULL,
- `endtime` varchar(100) default NULL,
- `description` varchar(500) default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=151 DEFAULT CHARSET=utf8;
1.導入相關依賴
父工程的pom文件,用來集中管理版本
pom.xml
2.搭建SSM環境
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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- id="MyWebApp" version="2.5">
- <display-name>zto-ssm</display-name>
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/applicationContext*.xml</param-value>
- </context-param>
- <!--Spring的ApplicationContext 載入 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <!-- 編碼過濾器,以UTF8編碼,解決post亂碼問題 -->
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <servlet>
- <servlet-name>ssm</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- 自定義SpringMVC配置文件路徑 -->
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/zto-ssm.xml</param-value>
- </init-param>
- <!-- 隨容器自動啓動完成初始化 -->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>ssm</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- </web-app>
-
jdbc.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
- jdbc.username=root
- jdbc.password=123456
applicationContext.xml
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- 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-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
- <!-- 使用spring自帶的佔位符替換功能 -->
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <!-- 允許JVM參數覆蓋 -->
- <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
- <!-- 忽略沒有找到的資源文件 -->
- <property name="ignoreResourceNotFound" value="true" />
- <!-- 配置資源文件 -->
- <property name="locations">
- <list>
- <value>classpath:jdbc.properties</value>
- </list>
- </property>
- </bean>
-
- <context:component-scan base-package="cn.xyc" />
-
- <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
- destroy-method="close">
- <!-- 數據庫驅動 -->
- <property name="driverClass" value="${jdbc.driver}" />
- <!-- 相應驅動的jdbcUrl -->
- <property name="jdbcUrl" value="${jdbc.url}" />
- <!-- 數據庫的用戶名 -->
- <property name="username" value="${jdbc.username}" />
- <!-- 數據庫的密碼 -->
- <property name="password" value="${jdbc.password}" />
- <!-- 檢查數據庫連接池中空閒連接的間隔時間,單位是分,默認值:240,如果要取消則設置爲0 -->
- <property name="idleConnectionTestPeriod" value="60" />
- <!-- 連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置爲0 -->
- <property name="idleMaxAge" value="30" />
- <!-- 每個分區最大的連接數 -->
- <property name="maxConnectionsPerPartition" value="150" />
- <!-- 每個分區最小的連接數 -->
- <property name="minConnectionsPerPartition" value="5" />
- </bean>
-
- </beans>
applicationContext-mybatis.xml
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- 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-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
- <!-- 定義Mybatis的SqlSessionFactory -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <!-- 定義數據源 -->
- <property name="dataSource" ref="dataSource" />
- <!-- 指定mybatis全局配置文件 -->
- <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
- <!-- 掃描mappers目錄以及子目錄下的所有xml文件 -->
- <property name="mapperLocations" value="classpath:mybatis/mappers/**/*.xml" />
- <!-- 別名掃描包 -->
- <property name="typeAliasesPackage" value="cn.xyc.ssm.pojo"/>
- </bean>
-
- <!-- 定義Mapper接口掃描器 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="cn.xyc.ssm.mapper" />
- </bean>
-
- </beans>
applicationContext-transaction.xml
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
-
- <!-- 定義事務管理器 -->
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
-
- <!-- 定義事務策略 -->
- <tx:advice id="txAdvice" transaction-manager="transactionManager">
- <tx:attributes>
- <!--所有以query開頭的方法都是隻讀的 -->
- <tx:method name="query*" read-only="true" />
- <!--其他方法使用默認事務策略 -->
- <tx:method name="*" />
- </tx:attributes>
- </tx:advice>
-
- <aop:config>
- <!--pointcut元素定義一個切入點,execution中的第一個星號 用以匹配方法的返回類型,
- 這裏星號表明匹配所有返回類型。 com.abc.dao.*.*(..)表明匹配cn.xyc.ssm.service包下的所有類的所有
- 方法 -->
- <aop:pointcut id="myPointcut" expression="execution(* cn.xyc.ssm.service.*.*(..))" />
- <!--將定義好的事務處理策略應用到上述的切入點 -->
- <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
- </aop:config>
-
- </beans>
mybatis-config.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
- <settings>
- <!-- 開啓駝峯自動映射 -->
- <setting name="mapUnderscoreToCamelCase" value="true" />
- </settings>
-
-
- <!-- 配置分頁插件 -->
- <plugins>
- <plugin interceptor="com.github.pagehelper.PageHelper">
- <property name="dialect" value="mysql"/>
- <!-- 該參數默認爲false -->
- <!-- 設置爲true時,使用RowBounds分頁會進行count查詢 -->
- <property name="rowBoundsWithCount" value="true"/>
- </plugin>
- </plugins>
-
- </configuration>
zto-ssm.xml
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- 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-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
- <!-- 註解驅動 -->
- <mvc:annotation-driven />
-
- <!-- 定義Controller的掃描包 -->
- <context:component-scan base-package="cn.xyc.ssm.controller" />
-
- <!-- 定義視圖解析器 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/views/" />
- <property name="suffix" value=".jsp" />
- </bean>
-
- <!-- 處理靜態資源被「/」所攔截的問題 -->
- <mvc:default-servlet-handler />
-
- </beans>
ok,框架搭建完成,可以啓動一下看看是否正常,當然配置文件中掃描的包必須創建好
因爲上面配置了mapper掃描的xml,但是目前還沒有xml,所有會報錯。註釋掉就不會報錯了
2.mybatis逆向生成實體映射等.
init.properties
- #Mybatis Generator configuration
- project = E:/eclipse/workspace/zto-ssm/src/main/java
- #classPath=D:/maven/Reposeitory/com/oracle/ojdbc6/11.2.0.3.0/ojdbc6-11.2.0.3.0.jar
- classPath = D:/repository/mysql/mysql-connector-java/5.1.32/mysql-connector-java-5.1.32.jar
- jdbc_driver = com.mysql.jdbc.Driver
- jdbc_url = jdbc:mysql://127.0.0.1:3306/mybatis
- jdbc_user = root
- jdbc_password = 123456
GeneratorConfig.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
- <generatorConfiguration>
- <!-- 引入配置文件 -->
- <properties resource="init.properties"/>
-
- <!-- 指定數據連接驅動jar地址 -->
- <classPathEntry location="${classPath}" />
-
- <!-- 一個數據庫一個context -->
- <context id="infoGuardian">
- <!-- 註釋 -->
- <commentGenerator >
- <property name="suppressAllComments" value="true"/><!-- 是否取消註釋 -->
- </commentGenerator>
-
- <!-- jdbc連接 -->
- <jdbcConnection driverClass="${jdbc_driver}"
- connectionURL="${jdbc_url}" userId="${jdbc_user}"
- password="${jdbc_password}" />
-
- <!-- 類型轉換 -->
- <javaTypeResolver>
- <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
- <property name="forceBigDecimals" value="false"/>
- </javaTypeResolver>
-
- <!-- 生成實體類地址 -->
- <javaModelGenerator targetPackage="cn.xyc.ssm.pojo"
- targetProject="${project}" >
- <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
- <property name="enableSubPackages" value="false"/>
- <!-- 是否針對string類型的字段在set的時候進行trim調用 -->
- <property name="trimStrings" value="true"/>
- </javaModelGenerator>
-
- <!-- 生成mapxml文件 -->
- <sqlMapGenerator targetPackage="cn.xyc.ssm.mapper"
- targetProject="${project}" >
- <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
- <property name="enableSubPackages" value="false" />
- </sqlMapGenerator>
-
- <!-- 生成mapxml對應client,也就是接口dao -->
- <javaClientGenerator targetPackage="cn.xyc.ssm.mapper"
- targetProject="${project}" type="XMLMAPPER" >
- <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
- <property name="enableSubPackages" value="false" />
- </javaClientGenerator>
-
- <!-- 配置表信息 -->
- <table schema="" tableName="user"
- domainObjectName="User" enableCountByExample="true"
- enableDeleteByExample="true" enableSelectByExample="true"
- enableUpdateByExample="true" selectByExampleQueryId="true">
- <!-- schema即爲數據庫名 tableName爲對應的數據庫表 domainObjectName是要生成的實體類 enable*ByExample
- 是否生成 example類 -->
- <!-- 忽略列,不生成bean 字段
- <ignoreColumn column="CLASS" />-->
- <!-- 指定列的java數據類型
- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />-->
- </table>
- </context>
- </generatorConfiguration>
pom文件中必須加上相關插件,上面已經有了.
運行maven命令:
mybatis-generator:generate 會生成相關文件,將映射文件移動到mybatis/mappers下面
3.Junit測試SSM框架
先添加日誌
log4j.properties
- log4j.rootLogger=DEBUG,A1
- log4j.logger.org.mybatis = DEBUG
- log4j.appender.A1=org.apache.log4j.ConsoleAppender
- log4j.appender.A1.layout=org.apache.log4j.PatternLayout
- log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
TestSSM.java
- package cn.xyc.ssm;
-
- import java.util.List;
-
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- import cn.xyc.ssm.mapper.UserMapper;
- import cn.xyc.ssm.pojo.User;
-
-
- /**
- *
- * @ClassName: TestMyBatis
- * @Description: 測試ssm框架
- * @author: xyc
- * @date: 2017年2月13日 下午7:53:09
- *
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:spring/*.xml" })
- public class TestSSM {
-
- @Autowired
- private UserMapper userMapper;
-
- /**
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- // 初始化SPring容器
- //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml",
- // "applicationContext-mybatis.xml");
- // 從容器中獲取SqlSessionFactory
- // SqlSessionFactory sqlSessionFactory =
- // applicationContext.getBean(SqlSessionFactory.class);
-
- // SqlSession sqlSession = sqlSessionFactory.openSession(true);
- // this.userMapper = sqlSession.getMapper(UserMapper.class);
- //this.userMapper = applicationContext.getBean(UserMapper.class);
- }
-
-
- @Test
- public void test1() {
-
- List<User> queryAll = userMapper.queryAll();
- for (User user : queryAll) {
- System.out.println(user);
- }
- }
- }
結果:
導入jquery-easyui-1.2.6類庫就可以直接使用easyUI了
commons.js
- // 自定義的校驗器
- $.extend($.fn.validatebox.defaults.rules, {
- midLength : {
- validator : function(value, param) {
- return value.length >= param[0] && value.length <= param[1];
- },
- message : ''
- },
- equalLength : {
- validator : function(value, param) {
- return value.length == param[0];
- },
- message : '密碼必須爲4個字符!'
- }
- });
-
- $.extend($.fn.datagrid.defaults.editors, {
- datetimebox : {
- init : function(container, options) {
- var box = $('<input />').appendTo(container);
- box.datetimebox(options);
- return box;
- },
- getValue : function(target) {
- return $(target).datetimebox('getValue');
- },
- setValue : function(target, value) {
- $(target).datetimebox('setValue', value);
- },
- resize : function(target, width) {
- var box = $(target);
- box.datetimebox('resize', width);
- },
- destroy : function(target) {
- $(target).datetimebox('destroy');
- }
- }
- });
index.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript" src="/js/jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script>
- <link rel="stylesheet" type="text/css" href="/js/jquery-easyui-1.2.6/themes/default/easyui.css" />
- <link rel="stylesheet" type="text/css" href="/js/jquery-easyui-1.2.6/themes/icon.css" />
- <script type="text/javascript" src="/js/jquery-easyui-1.2.6/jquery.easyui.min.js"></script>
- <script type="text/javascript" src="/js/jquery-easyui-1.2.6/locale/easyui-lang-zh_CN.js"></script>
- <script type="text/javascript" src="/js/commons.js"></script>
- <script type="text/javascript">
- $(function(){
-
- //-----------------------------對於form表單的驗證 ---------------------------------------------------------------------------
- $('#username').numberbox({
- min:0 , //允許的最小值
- max:150 , //允許的最大值
- required:true , //必填字段 定義是否字段應被輸入
- missingMessage:'用戶名必填!' , //當文本框是空時出現的提示文字
- precision:0 //顯示在小數點後面的最大精度
- });
- //數值驗證組件
- $('#age').numberbox({
- min:0 , //允許的最小值
- max:150 , //允許的最大值
- required:true , //必填字段 定義是否字段應被輸入
- missingMessage:'年齡必填!' , //當文本框是空時出現的提示文字
- precision:0 //顯示在小數點後面的最大精度
- });
-
- //日期組件
- $('#birthday').datebox({
- required:true , //必填字段 定義是否字段應被輸入
- missingMessage:'生日必填!' , //當文本框是空時出現的提示文字
- editable:false //定義是否用戶可以往文本域中直接輸入文字
- });
-
- $('#salary').numberbox({
- min:1000 ,
- max:20000 ,
- required:true ,
- missingMessage:'薪水必填!' ,
- precision:2
- });
-
- //日期時間組件
- $('#startTime,#endTime').datetimebox({
- required:true ,
- missingMessage:'時間必填!' ,
- editable:false //定義是否用戶可以往文本域中直接輸入文字
- });
-
-
- var flag ; //undefined 判斷新增和修改方法
-
- ///---------------------datagrid部分----------------------------------------------------------------------------------
- $('#tt').datagrid({
- idField: 'id', //只要創建數據表格 就必須要加 ifField
- url: 'user/queryUserByPage',
- title: '用戶信息',
- //width: '1000',
- height:450 ,
- fitColumns: true, //寬度自適應
- striped: true , //隔行變色特性
- rownumbers:true, //顯示行號
- //singleSelect:true , //單選模式
- loadMsg: '數據正在加載,請耐心的等待...' ,
- frozenColumns:[[ //凍結列特性 ,不要與fitColumns 特性一起使用
- { //如果需要多選,需要禁止單選模式
- field:'ck' ,
- width:50 ,
- checkbox: true
- }
- ]],
- columns:[[
- {field:'id',title:'編號',width:120},
- {
- field:'username',
- title:'用戶名',
- width:120,
- align:'center' , //居中顯示
- styler:function(value , record){
- if(value == 'admin'){
- //return 'background:blue;'; //如果用戶名爲admin,變藍色
- }
- }
- },
- {
- field:'password',
- title:'密碼',
- width:120,
- hidden: true //將密碼隱藏
- },
- {
- field:'sex',
- title:'性別',
- width:120,
- formatter:function(value , record , index){
- if(value == 1){
- return '<span style=color:red; >男</span>' ;
- } else if( value == 2){
- return '<span style=color:green; >女</span>' ;
- }
- //console.info(value);
- //console.info(record);
- //console.info(index);
- }
- },
- {field:'age',title:'年齡',width:120},
- {field:'birthday',title:'生日',width:120},
- {
- field:'city',
- title:'城市',
- width:120,
- formatter:function(value , record , index){
- /*
- if(value==1){
- return '北京';
- } else if(value == 2){
- return '上海';
- } else if(value == 3){
- return '深圳';
- } else if(value == 4){
- return '長春';
- }
- */
- var str = '';
- $.ajax({
- type:'post' ,
- url : 'user/getCityName' ,
- /* url : 'user/getCityName2' , */
- cache:false ,
- async: false , //同步請求
- data:{id:value},
- dataType:'json' ,
- success:function(result){
- //str = result ; //dataType:'text'
- str = result.name ; //dataType:'json'
- }
- });
- return str ;
- }
-
- },
- {field:'salary',title:'薪資',width:120},
- {field:'starttime',title:'創建日期',width:120},
- {field:'endtime',title:'結束日期',width:120},
- {
- field:'description',
- title:'描述',
- width:120,
- formatter:function(value , record , index){
- return '<span title='+value+'>'+value+'</span>';
- }
- },
- ]],
- pagination: true , //在底部顯示分頁欄
- pageSize: 10 , //每頁顯示多少個
- pageList:[5,10,15,20,50], //初始化頁面尺寸的選擇列表
- toolbar:[
- {
- iconCls:"icon-add",//按鈕上的圖標
- text:"添加用戶", //按鈕的文字
- handler:function(){
- flag = 'add'; //改變flag的值
- //$('#myform').find('input[name!=sex]').val("");
- $('#myform').get(0).reset();
- //$('#myform').form('clear');
- $("#mydialog").dialog("open");
- }
- },
- {
- iconCls:"icon-edit",//按鈕上的圖標
- text:"編輯用戶",//按鈕的文字
- handler:function(){
- flag = 'edit'; //改變flag的值
- var arr =$('#tt').datagrid('getSelections'); //獲取被選中的行,返回的是數組
- if(arr.length != 1){
- $.messager.show({
- title:'提示信息!',
- msg:'只能選擇一行記錄進行修改!'
- });
- } else {
- $('#mydialog').dialog({
- title:'修改用戶'
- });
- $('#mydialog').dialog('open'); //打開窗口
- $('#myform').get(0).reset(); //清空表單數據
- $('#myform').form('load',{ //調用load方法把所選中的數據load到表單中,非常方便
- id:arr[0].id ,
- username:arr[0].username ,
- password:arr[0].password ,
- sex:arr[0].sex ,
- age:arr[0].age ,
- birthday:arr[0].birthday ,
- city:arr[0].city ,
- salary:arr[0].salary ,
- starttime:arr[0].starttime,
- endtime:arr[0].endtime ,
- description:arr[0].description
- });
- }
- }
- },
- {
- iconCls:"icon-remove",//按鈕上的圖標
- text:"刪除用戶",//按鈕的文字
- handler:function(){
- //console.log('刪除'); //在瀏覽器控制檯打印日誌
- var arr =$('#tt').datagrid('getSelections');
- if(arr.length <=0){
- $.messager.show({
- title:'提示信息!',
- msg:'至少選擇一行記錄進行刪除!'
- });
- } else {
-
- $.messager.confirm('提示信息' , '確認刪除?' , function(r){
- if(r){
- var ids = '';
- for(var i =0 ;i<arr.length;i++){
- ids += arr[i].id + ',' ;
- }
- ids = ids.substring(0 , ids.length-1);
- $.post('user/delete' , {ids:ids} , function(result){
- //1 刷新數據表格
- $('#tt').datagrid('reload');
- //2 清空idField
- $('#tt').datagrid('clearSelections'); //unselectAll取消選中當前頁所有的行。 clearSelections清除所有的選擇。
- //3 給提示信息
- $.messager.show({
- title:result.status ,
- msg:result.message
- });
- });
- } else {
- return ;
- }
- });
- }
- }
- },
- {
- iconCls:"icon-search",//按鈕上的圖標
- text:"查詢用戶",//按鈕的文字
- handler:function(){
- //console.log('查詢'); //在瀏覽器控制檯打印日誌
- $('#lay').layout('expand' , 'north');
- }
- }
- ]
- });
-
-
-
-
- //-----------提交表單方法-------------------------------------------------------------------------------------------------------------
- $('#btn1').click(function(){
- if($('#myform').form('validate')){
- $.ajax({
- type: 'post' ,
- url: flag=='add'?'user/save':'user/update' ,
- //url:'user/save',
- cache:false ,
- data:$('#myform').serialize() ,
- dataType:'json' ,
- success:function(result){
- //1 關閉窗口
- $('#mydialog').dialog('close');
- //2刷新datagrid
- $('#tt').datagrid('reload');
- //3 提示信息
- $.messager.show({
- title:result.status ,
- msg:result.message
- });
- } ,
- error:function(result){
- $.meesager.show({
- title:result.status ,
- msg:result.message
- });
- }
- });
- } else {
- $.messager.show({
- title:'提示信息!' ,
- msg:'數據驗證不通過,不能保存!'
- });
- }
- });
-
- /**
- * 關閉窗口方法
- */
- $('#btn2').click(function(){
- $('#mydialog').dialog('close');
- });
-
-
- $('#searchbtn').click(function(){
- $('#tt').datagrid('load' ,serializeForm($('#mysearch')));
- });
-
- //查詢時清空按鈕
- $('#clearbtn').click(function(){
- $('#mysearch').form('clear');
- $('#tt').datagrid('load' ,{}); //清空數據
- });
- });
-
- //js方法:序列化表單
- function serializeForm(form){
- var obj = {};
- $.each(form.serializeArray(),function(index){
- if(obj[this['name']]){
- obj[this['name']] = obj[this['name']] + ','+this['value'];
- } else {
- obj[this['name']] =this['value'];
- }
- });
- return obj;
- }
- </script>
- </head>
- <body>
-
- <div id="lay" class="easyui-layout" fit=true style="width: 100%; height: 1000px">
- <!-- 用戶搜索部分 -->
- <div region="north" title="用戶查詢" split="true" collapsed=true style="height: 100px;">
- <div style="margin-left: 100px;margin-top: 20px;">
- <form id="mysearch" method="post">
- 用戶名:<input name="username" class="easyui-validatebox" value="" />
-
- 開始時間:<input name="starttime" class="easyui-datetimebox" editable="false" style="width:160px;" value="" />
- 結束時間:<input name="endtime" class="easyui-datetimebox" editable="false" style="width:160px;" value="" />
-
- <a id="searchbtn" class="easyui-linkbutton">查詢</a> <a id="clearbtn" class="easyui-linkbutton">清空</a>
- </form>
- </div>
- </div>
- <!-- 用戶列表部分 -->
- <div region="center" style="padding: 5px; background: #eee;">