码云 Gitee IDE 全新上线——支持 Git 管理的轻量在线编码环境
Watch Star Fork

Remenber_Ray / mybatisplus-spring-mvcJava

加入码云
与超过 300 万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
暂无描述
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README.md 56.15 KB

mybatisplus-spring-mvc

集成Mybatis-Plus

Mybatis-Plus 的集成非常简单,对于 Spring,我们仅仅需要把 Mybatis 自带的MybatisSqlSessionFactoryBean替换为 MP 自带的即可。

代码生成器:点击跳转

  • 提取常用配置,可直接修改使用
  • 提供两个版本,分别为 J版R版,区别在xxMapper.xml 生成的位置不同,数据层包名也不同

项目地址:点击跳转

  • 注意:编程思维的养成

官方文档:点击跳转 本人博客:点击跳转

开始

pom.xml

添加相关依赖

配置可变版本号

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ray</groupId>
  <artifactId>mybatisplus-spring-mvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>mybatisplus-spring-mvc Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <!--
  配置可变版本号,也就是常说的版本管理
  要针对某个依赖进行升级的时候只需要更改下面对应的版本号即可
  -->
  <properties>
    <spring.version>5.0.0.RELEASE</spring.version>
    <javax.servlet.version>3.1.0</javax.servlet.version>
    <junit.version>4.12</junit.version>
    <druid.version>1.1.0</druid.version>
    <fastjson.version>1.2.8</fastjson.version>
    <mybaitsplus.version>2.3</mybaitsplus.version>
    <mysql.version>5.1.38</mysql.version>
    <aspectjweaver.version>1.8.8</aspectjweaver.version>
    <jstl.version>1.2</jstl.version>
    <log4j.version>2.11.0</log4j.version>
    <slf4j.version>1.7.25</slf4j.version>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- JUnit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>

    <!-- Spring MVC -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>

    <!-- AOP -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectjweaver.version}</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${javax.servlet.version}</version>
    </dependency>


    <!-- Mybatis-Plus -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>${mybaitsplus.version}</version>
    </dependency>
    <!-- 模板引擎 -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity-engine-core</artifactId>
      <version>2.0</version>
    </dependency>
    <!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.23</version>
    </dependency>

    <!-- Mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <!-- Druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <!-- FastJson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>

    <!-- Log4j2 -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <!--Log4j2和slf4j桥接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <!-- slf4j -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>mybatisplus-spring-mvc</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

web.xml

替换404页面,这里要使用绝对路径

登录Druid需要验证: admin/admin

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">


  <display-name>Archetype Created Web Application</display-name>

  <!--加载Spring配置文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring.xml</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>

  <!--Spring监听器-->
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <!--防止Spring内存溢出监听器-->
  <listener>
    <listener-class>
      org.springframework.web.util.IntrospectorCleanupListener
    </listener-class>
  </listener>

  <!--Spring MVC-->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <description>SpringMVC</description>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--Session超时时间-->
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

  <!--Druid-->
  <servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>
      com.alibaba.druid.support.http.StatViewServlet
    </servlet-class>
    <!--不允许清空统计数据-->
    <init-param>
      <param-name>resetEnable</param-name>
      <param-value>false</param-value>
    </init-param>
    <!-- 用户名 -->
    <init-param>
      <param-name>loginUsername</param-name>
      <param-value>admin</param-value>
    </init-param>
    <!-- 密码 -->
    <init-param>
      <param-name>loginPassword</param-name>
      <param-value>admin</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>

  <!--替换404页面-->
  <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
  </error-page>
</web-app>

jdbc.properties

MysqlDruid 常用配置

# Mysql
## 数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
## 数据库地址
jdbc.url=jdbc:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf8
## 数据库名称
jdbc.username=root
## 数据库密码
jdbc.password=root


# Druid
## 配置初始化大小、最小、最大
druid.initialSize=1
druid.minIdle=1
druid.maxActive=20
## 配置获取连接等待超时的时间
druid.maxWait=60000
## 配置间隔多久才进行一次检测,检测需要关闭的空闲连接
druid.timeBetweenEvictionRunsMillis=60000
## 配置一个连接在池中最小生存的时间
druid.minEvictableIdleTimeMillis=300000
## 验证连接有效与否的SQL,不同的数据配置不同
druid.validationQuery=SELECT 'x'
## 检测连接是否有效
druid.testWhileIdle=true
druid.testOnBorrow=true
druid.testOnReturn=false
## 打开PSCache,mysql可以配置为false
druid.poolPreparedStatements=false
druid.maxPoolPreparedStatementPerConnectionSize=20
## 这里配置提交方式
druid.defaultAutoCommit=true
## 合并多个DruidDataSource的监控数据
druid.useGlobalDataSourceStat=true
## 开启Druid的监控统计功能
druid.filters=stat,wall

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>

        <Console name="Console" target="SYSTEM_OUT">
            <!--只接受程序中DEBUG级别的日志进行处理-->
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss.SSS}] %-5level %class{36} %L %M - %msg%xEx%n"/>
        </Console>

        <!--处理DEBUG级别的日志,并把该日志放到logs/debug.log文件中-->
        <!--打印出DEBUG级别日志,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
        <RollingFile name="RollingFileDebug" fileName="./logs/debug.log"
                     filePattern="logs/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="DEBUG"/>
                <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout
                    pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>

        <!--处理INFO级别的日志,并把该日志放到logs/info.log文件中-->
        <RollingFile name="RollingFileInfo" fileName="./logs/info.log"
                     filePattern="logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <!--只接受INFO级别的日志,其余的全部拒绝处理-->
                <ThresholdFilter level="INFO"/>
                <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout
                    pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>

        <!--处理WARN级别的日志,并把该日志放到logs/warn.log文件中-->
        <RollingFile name="RollingFileWarn" fileName="./logs/warn.log"
                     filePattern="logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="WARN"/>
                <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout
                    pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>

        <!--处理error级别的日志,并把该日志放到logs/error.log文件中-->
        <RollingFile name="RollingFileError" fileName="./logs/error.log"
                     filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
            <ThresholdFilter level="ERROR"/>
            <PatternLayout
                    pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>

        <!--druid的日志记录追加器-->
        <RollingFile name="druidSqlRollingFile" fileName="./logs/druid-sql.log"
                     filePattern="logs/$${date:yyyy-MM}/api-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %L %M - %msg%xEx%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>
    </appenders>

    <loggers>
        <root level="DEBUG">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
            <appender-ref ref="RollingFileDebug"/>
        </root>

        <!--记录druid-sql的记录-->
        <logger name="druid.sql.Statement" level="debug" additivity="false">
            <appender-ref ref="druidSqlRollingFile"/>
        </logger>
        <logger name="druid.sql.Statement" level="debug" additivity="false">
            <appender-ref ref="druidSqlRollingFile"/>
        </logger>

        <!--log4j2 自带过滤日志-->
        <Logger name="org.apache.catalina.startup.DigesterFactory" level="error" />
        <Logger name="org.apache.catalina.util.LifecycleBase" level="error" />
        <Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn" />
        <logger name="org.apache.sshd.common.util.SecurityUtils" level="warn"/>
        <Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn" />
        <Logger name="org.crsh.plugin" level="warn" />
        <logger name="org.crsh.ssh" level="warn"/>
        <Logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="error" />
        <Logger name="org.hibernate.validator.internal.util.Version" level="warn" />
        <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="warn"/>
        <logger name="org.springframework.boot.actuate.endpoint.jmx" level="warn"/>
        <logger name="org.thymeleaf" level="warn"/>
    </loggers>
</configuration>

脚本初始化

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user`  (
  `id` bigint(20) NOT NULL COMMENT '用户ID',
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
  `age` int(3) NULL DEFAULT NULL COMMENT '用户年龄',
  `type` int(1) NULL DEFAULT 0 COMMENT '0、禁用 1、正常, 如果使用tinyint(1),mysql连接没加tinyInt1isBit=false,默认mysql驱动会把值转成boolean',
  `ctime` datetime NULL DEFAULT NULL COMMENT '自定义填充的创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '系统用户表' ROW_FORMAT = Compact;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES (784972358981328902, 'Tom', 24, 1, '2017-06-25 20:53:33');
INSERT INTO `sys_user` VALUES (784972358981328903, 'Jammy', 21, 1, '2017-06-25 20:53:37');

SET FOREIGN_KEY_CHECKS = 1;

Spring配置文件

spring-mybatis.xml

把 Mybatis 自带的MybatisSqlSessionFactoryBean替换为 MP 自带的即可。

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">

添加分页查询插件

<!--分页查询插件-->
<bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
    <property name="dialectType" value="mysql" />
</bean>

定义 MP 全局策略

    <!--定义 MP 全局策略-->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!-- 定义主键策略:
            AUTO->`0`("数据库ID自增")
            INPUT->`1`(用户输入ID")
            ID_WORKER->`2`("全局唯一ID")
            UUID->`3`("全局唯一ID")
       -->
        <property name="idType" value="2" />

        <!--公共字段填充处理器-->
        <property name="metaObjectHandler">

            <!-- 自定义处理器 -->
            <bean class="com.ray.common.MyMetaObjectHandler"/>
        </property>
    </bean>

完整示例

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 1.配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 配置连接池属性 -->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${druid.initialSize}"/>
        <property name="minIdle" value="${druid.minIdle}"/>
        <property name="maxActive" value="${druid.maxActive}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${druid.maxWait}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/>

        <!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
        <property name="validationQuery" value="${druid.validationQuery}" />

        <!-- 如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效 -->
        <property name="testWhileIdle" value="${druid.testWhileIdle}"/>

        <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
        <property name="testOnBorrow" value="${druid.testOnBorrow}"/>
        <property name="testOnReturn" value="${druid.testOnReturn}"/>

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <!-- 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。 -->
        <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}"/>

        <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
        <property name="defaultAutoCommit" value="${druid.defaultAutoCommit}" />

        <!-- 合并多个DruidDataSource的监控数据 -->
        <property name="useGlobalDataSourceStat" value="${druid.useGlobalDataSourceStat}"/>

        <!-- 开启Druid的监控统计功能,StatFilter可以和其他的Filter配置使用 -->
        <property name="filters" value="${druid.filters}"/>

        <!-- proxyFilters属性配置,通过bean的方式配置 -->
        <property name="proxyFilters">
            <list>
                <ref bean="log4j2-filter"/>
            </list>
        </property>
    </bean>

    <!-- 上面的druid的配置 -->
    <bean id="log4j2-filter" class="com.alibaba.druid.filter.logging.Log4j2Filter">
        <!-- 所有连接相关的日志 -->
        <property name="connectionLogEnabled" value="false"/>
        <!-- 所有Statement相关的日志 -->
        <property name="statementLogEnabled" value="false"/>
        <!-- 是否显示结果集 -->
        <property name="resultSetLogEnabled" value="true"/>
        <!-- 是否显示SQL语句 -->
        <property name="statementExecutableSqlLogEnable" value="true"/>
    </bean>

    <!-- 2.Spring整合MyBatis的完美结合,更多查看文档:http://mp.baomidou.com  -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描实体类,使用别名 -->
        <property name="typeAliasesPackage" value="com.ray.entity"/>
        <!--配置扫描通用枚举-->
        <property name="typeEnumsPackage" value="com.ray.enums"/>
        <!-- 自动扫描Mapper.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- 插件配置项 -->
        <property name="plugins">
            <array>
                <!--分页查询插件-->
                <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
                    <property name="dialectType" value="mysql" />
                </bean>
            </array>
        </property>
        <!--全局配置注入-->
        <property name="globalConfig" ref="globalConfig" />
    </bean>

    <!--定义 MP 全局策略-->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!-- 定义主键策略:
            AUTO->`0`("数据库ID自增")
            INPUT->`1`(用户输入ID")
            ID_WORKER->`2`("全局唯一ID")
            UUID->`3`("全局唯一ID")
       -->
        <property name="idType" value="2" />

        <!--公共字段填充处理器-->
        <property name="metaObjectHandler">

            <!-- 自定义处理器 -->
            <bean class="com.ray.common.MyMetaObjectHandler"/>
        </property>
    </bean>

    <!-- 3.MyBatis 动态扫描  -->
    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.ray.dao"/>
    </bean>
</beans>

spring-mvc.xml

静态资源配置

    <!--静态资源由WEB服务器默认的Servlet来处理-->
    <mvc:default-servlet-handler/>

    <!--静态资源配置-->
    <mvc:resources mapping="/views/**" location="/WEB-INF/views/" />
    <mvc:resources mapping="/images/**" location="/static/images/" />
    <mvc:resources mapping="/resources/**" location="/static/resources/"/>

完整示例

<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--自动扫描包-->
    <context:component-scan base-package="com.ray.controller"/>

    <!-- FastJson注入 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
                        <!-- 避免循环引用 -->
                        <value>DisableCircularReferenceDetect</value>
                        <!-- 是否输出值为null的字段 -->
                        <value>WriteMapNullValue</value>
                        <!-- 数值字段如果为null,输出为0,而非null -->
                        <value>WriteNullNumberAsZero</value>
                        <!-- 字符类型字段如果为null,输出为"",而非null  -->
                        <value>WriteNullStringAsEmpty</value>
                        <!-- List字段如果为null,输出为[],而非null -->
                        <value>WriteNullListAsEmpty</value>
                        <!-- Boolean字段如果为null,输出为false,而非null -->
                        <value>WriteNullBooleanAsFalse</value>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--静态资源由WEB服务器默认的Servlet来处理-->
    <mvc:default-servlet-handler/>

    <!--静态资源配置-->
    <mvc:resources mapping="/views/**" location="/WEB-INF/views/" />
    <mvc:resources mapping="/images/**" location="/static/images/" />
    <mvc:resources mapping="/resources/**" location="/static/resources/"/>

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

spring-service.xml

基于注解的方式

@Transactional

<tx:annotation-driven transaction-manager="transactionManager"/>

基于AspectJ的XML声明式

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            ……
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.ray.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

完整示例

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 1.配置事务管理 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--2.配置事务的通知(事务的增强) [提供两种实现方法]-->

    <!-- 方法一:
            基于注解的方式需要在业务层上添加一个@Transactional的注解。
    -->
    <!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

    <!-- 方法二:
            基于AspectJ的XML声明式事务管理
            在这种方式下Dao和Service的代码也不会改变(推荐)
     -->
    <!-- 事务管理 属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--propagation  :事务传播行为-->
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <!--read-only    :只读-->
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置事务切面,使得上面的事务配置对service接口的所有操作有效 -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.ray.service.*.*(..))"/>
        <!-- 配置切面 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

spring.xml

引入属性文件

<context:property-placeholder location="classpath:jdbc.properties"/>

完整示例

<?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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--引入属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--Service包(自动注入)-->
    <context:component-scan base-package="com.ray.service"/>

    <!--导入相关配置-->
    <import resource="classpath:spring/spring-mybatis.xml" />
    <import resource="classpath:spring/spring-service.xml" />
</beans>

Common公共类

封装Json返回信息

package com.ray.common.result;

/**
 * @author Ray
 * @date 2018/7/18 0018
 * 封装Json返回信息
 */
public class JsonResult {

    private boolean success;
    private String status;
    private String msg;
    private Object obj;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
}

自定义填充字段

package com.ray.common;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Ray
 * @date 2018/7/18 0018
 * 实现元对象处理器接口: com.baomidou.mybatisplus.mapper.MetaObjectHandler
 * 自定义填充公共 ctime 字段
 */
public class MyMetaObjectHandler extends MetaObjectHandler {

    /**
     * 测试 user 表 ctime 字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 更多查看源码测试用例
        System.out.println("*************************");
        System.out.println("insert fill");
        System.out.println("*************************");

        Date date = new Date();
        this.setFieldValByName("ctime", date, metaObject);
        System.out.println("当前时间: " + date );
    }

    @Override
    public boolean openUpdateFill() {
        return false; // 关闭更新填充(默认true)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 由于关闭更新填充、这里不执行
        System.out.println("*************************");
        System.out.println("update fill");
        System.out.println("*************************");
    }
}

Enum枚举类

解决了繁琐的配置,让 mybatis 优雅的使用枚举属性 自定义枚举实现 IEnum 接口,申明自动注入为通用枚举转换处理器

完整示例

package com.ray.enums;

import com.baomidou.mybatisplus.enums.IEnum;

import java.io.Serializable;

/**
 * @author Ray
 * @date 2018/7/18 0018
 * 解决了繁琐的配置,让 mybatis 优雅的使用枚举属性
 * 自定义枚举实现 IEnum 接口,申明自动注入为通用枚举转换处理器
 */
public enum TypeEnum implements IEnum {

    DISABLED(0,"禁用"),
    NORMAL(1,"正常");

    private final int value;
    private final String desc;

    TypeEnum(final int value, final String desc){
        this.value = value;
        this.desc = desc;
    }

    @Override
    public Serializable getValue() {
        return this.value;
    }

    // Jackson 注解为 JsonValue 返回中文 json 描述
    public String getDesc(){
        return this.desc;
    }
}

Entity实体类

使用枚举类型属性

    /**
     * 0、禁用 1、正常, 如果使用tinyint(1),mysql连接没加tinyInt1isBit=false,默认mysql驱动会把值转成boolean
     */
    private TypeEnum type;

使用自动填充字段

    private TypeEnum type;
    /**
     * 注意!这里需要标记为填充字段
     * 注入数据库时间 , insert = "now()"
     */
    @TableField(fill = FieldFill.INSERT)
    private Date ctime;

完整示例

package com.ray.entity;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.ray.enums.TypeEnum;

import java.util.Date;
import java.io.Serializable;

/**
 * <p>
 * 系统用户表
 * </p>
 *
 * @author Ray
 * @since 2018-07-18
 */
@TableName("sys_user")
public class SysUser implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 用户ID
     */
    private Long id;
    /**
     * 用户名
     */
    private String name;
    /**
     * 用户年龄
     */
    private Integer age;
    /**
     * 0、禁用 1、正常, 如果使用tinyint(1),mysql连接没加tinyInt1isBit=false,默认mysql驱动会把值转成boolean
     */
    private TypeEnum type;
    /**
     * 注意!这里需要标记为填充字段
     * 注入数据库时间 , insert = "now()"
     */
    @TableField(fill = FieldFill.INSERT)
    private Date ctime;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public TypeEnum getType() {
        return type;
    }

    public void setType(TypeEnum type) {
        this.type = type;
    }

    public Date getCtime() {
        return ctime;
    }

    public void setCtime(Date ctime) {
        this.ctime = ctime;
    }

    @Override
    public String toString() {
        return "SysUser{" +
        ", id=" + id +
        ", name=" + name +
        ", age=" + age +
        ", type=" + type +
        ", ctime=" + ctime +
        "}";
    }
}

Dao数据访问层

继承BaseMapper

集成基本的 CRUD 操作,当然我们可用的 API 远不止这几个,我们提供了多达 17 个方法给大家使用,可以极其方便的实现单一、批量、分页等操作

public interface SysUserDao extends BaseMapper<SysUser> {

}

完整示例

package com.ray.dao;

import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.ray.entity.SysUser;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.ray.enums.TypeEnum;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 系统用户表 Mapper 接口
 * </p>
 *
 * @author Ray
 * @since 2018-07-18
 */
public interface SysUserDao extends BaseMapper<SysUser> {

    /**
     * Select注解引用自 SysUserMapper 中的id
     * 分页示例
     */
    @Select("selectSysUserList")
    List<SysUser> selectSysUserList(Pagination page, TypeEnum type); //Pagination 为Mybatis plus分页插件的实体
}

Mapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ray.dao.SysUserDao">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.ray.entity.SysUser">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="age" property="age" />
        <result column="type" property="type" />
        <result column="ctime" property="ctime" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, name, age, type, ctime
    </sql>

    <!--分页示例-->
    <select id="selectSysUserList" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM
        sys_user
        WHERE
        type = #{type}
    </select>
</mapper>

Service服务层

继承IService

package com.ray.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.ray.entity.SysUser;
import com.baomidou.mybatisplus.service.IService;
import com.ray.enums.TypeEnum;

/**
 * <p>
 * 系统用户表 服务类
 * </p>
 *
 * @author Ray
 * @since 2018-07-18
 */
public interface SysUserService extends IService<SysUser> {

    // 分页示例
    Page<SysUser> selectSysUserPage(Page<SysUser> page, TypeEnum type);
}

Service实现

继承 ServiceImpl 实现 SysUserService

package com.ray.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.ray.entity.SysUser;
import com.ray.dao.SysUserDao;
import com.ray.enums.TypeEnum;
import com.ray.service.SysUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author Ray
 * @since 2018-07-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    // 分页示例
    @Override
    public Page<SysUser> selectSysUserPage(Page<SysUser> page, TypeEnum type){
        page.setRecords(baseMapper.selectSysUserList(page, type));
        return page;
    }
}

Controller控制层

BaseController

基础控制器

package com.ray.controller;

import com.ray.common.result.JsonResult;

/**
 * @author Ray
 * @date 2018/7/18 0018
 * 基础控制器
 */
public class BaseController {

    /**
     * 渲染失败数据
     */
    protected JsonResult renderError(){
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus("500");
        return result;
    }

    /**
     * 渲染失败数据(带信息)
     */
    protected JsonResult renderError(String msg){
        JsonResult result = renderError();
        result.setMsg(msg);
        return result;
    }

    /**
     * 渲染成功数据
     */
    protected JsonResult renderSuccess(){
        JsonResult result = new JsonResult();
        result.setSuccess(true);
        result.setStatus("200");
        return result;
    }

    /**
     * 渲染成功数据(带信息)
     */
    protected JsonResult renderSuccess(String msg){
        JsonResult result = renderSuccess();
        result.setMsg(msg);
        return result;
    }

    /**
     * 渲染成功数据(带数据)
     */
    protected  JsonResult renderSuccess(Object obj){
        JsonResult result = renderSuccess();
        result.setObj(obj);
        return result;
    }
}

SysUserController

package com.ray.controller;


import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.plugins.Page;
import com.ray.entity.SysUser;
import com.ray.enums.TypeEnum;
import com.ray.service.SysUserService;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author Ray
 * @since 2018-07-18
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

    private final SysUserService sysUserService;

    /**
     * 构造器方式注入(推荐)
     */
    @Autowired
    public SysUserController(SysUserService sysUserService){
        this.sysUserService = sysUserService;
    }

    /**
     * 显示主页面
     */
    @RequestMapping("/index")
    public ModelAndView index(ModelAndView modelAndView){
        modelAndView.setViewName("index");
        // 数据集合 list
        modelAndView.addObject("list", sysUserService.selectList(null));
        return modelAndView;
    }

    /**
     * 显示新增/修改页面(二合一)
     */
    @RequestMapping("/preSave")
    public ModelAndView preSave(ModelAndView modelAndView, @RequestParam(value = "id", required = false) Long id){
        modelAndView.setViewName("save");
        // 如果id不为空,则根据id查询用户信息
        if(id != null){
            modelAndView.addObject("user", sysUserService.selectById(id));
        }
        return modelAndView;
    }

    /**
     * 保存数据 json
     * 用于新增、修改数据
     */
    @ResponseBody
    @RequestMapping("/save")
    public Object save(SysUser sysUser){
        sysUser.setType(TypeEnum.DISABLED);
        if(sysUser.getId() == null){
            return sysUserService.insert(sysUser) ? renderSuccess("添加成功") : renderError("添加失败");
        }else{
            return sysUserService.updateById(sysUser) ? renderSuccess("修改成功") : renderError("修改失败");
        }
    }

    /**
     * 删除数据 json
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(value = "id", required = true) Long id){
        return sysUserService.deleteById(id) ? renderSuccess("删除成功") : renderError("删除失败");
    }

    /**
     * 分页示例
     */
    @ResponseBody
    @RequestMapping("/page")
    public Object selectPage(){

        Page page = new Page(1,10);
        page = sysUserService.selectSysUserPage(page, TypeEnum.DISABLED );
        System.out.println("总数: " + page.getTotal());
        System.out.println("当前页: " + page.getCurrent());
        // 返回数据集合
        List<SysUser> list = page.getRecords();
        for (SysUser sysuser :
                list) {
            System.out.println(sysuser);
        }
        return page;
    }
}

页面视图

include.jsp

公共视图

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%--c 标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<%-- Jquery--%>
<script src="${ctx}/resources/jquery/jquery-2.2.3.min.js" type="text/javascript"></script>

<%-- Bootstrap --%>
<link href="${ctx}/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<script src="${ctx}/resources/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>

<%--返回首页--%>
<script>
    function toIndex() {
        window.location.href = '${ctx}/sysUser/index';
    }
</script>

index.jsp

主页

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%-- c 标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx"  value="${pageContext.request.contextPath}" />

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>用户列表</title>
    <%@ include file="common/include.jsp" %>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <br/>
                <div class="panel panel-default">
                    <div class="panel-body">
                        <button type="button" onclick="preSave()" class="btn btn-default">添加</button>
                    </div>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>姓名</th>
                                <th>年龄</th>
                                <th>类型</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach var="user" items="${list}">
                                <tr>
                                    <td>${user.id}</td>
                                    <td>${user.name}</td>
                                    <td>${user.age}</td>
                                    <td>${user.type}</td>
                                    <td>${user.ctime}</td>
                                    <td>
                                        <a href="javascript:void(0);" onclick="preSave('${user.id}')" title="编辑">
                                            <i class="glyphicon glyphicon-edit"></i>
                                        </a>
                                        <a href="javascript:void(0);" onclick="del('${user.id}')" title="删除">
                                            <i class="glyphicon glyphicon-remove"></i>
                                        </a>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function preSave(id) {
            if(id == undefined || id == null || id == ''){
                window.location.href = '${ctx}/sysUser/preSave';
            }else{
                window.location.href = '${ctx}/sysUser/preSave?id=' + id;
            }
        }

        function del(id) {
            $.ajax({
                type: "POST",
                url: '${ctx}/sysUser/delete',
                data:{
                    id:id
                },
                dataType: 'json',
                success: function (data) {
                    alert(data.msg);
                    if(data.success){
                        setTimeout('toIndex()',100);
                    }
                },
                error: function () {
                    alert("出错了,请重试!")
                }
            })
        }
    </script>
</body>
</html>

save.jsp

新增、修改页面

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

<%--c 标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>新增/编辑页面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <%@ include file="common/include.jsp" %>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <form id="form" role="form">
                    <input id="id" name="id" value="${user.id}" hidden="">
                    <div class="form-group">
                        <label for="name">姓名</label>
                        <input type="text" class="form-control" id="name" name="name" value="${user.name}" placeholder="请输入姓名"/>
                    </div>
                    <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="text" class="form-control" id="age" name="age" value="${user.age}" placeholder="请输入年龄"/>
                    </div>
                    <button type="button" onclick="save()" class="btn btn-default">保存</button>
                    <button type="reset" class="btn btn-default">取消</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        function save() {
            $.ajax({
                type: "POST",
                url: '${ctx}/sysUser/save',
                // 将表单序列化为键值对后提交
                data: $('#form').serialize(),
                dataType: 'json',
                success: function (data) {
                    alert(data.msg);
                    if(data.success){
                        setTimeout('toIndex()', 100);
                    }
                },
                error: function () {
                    alert("出错了,请重试!")
                }
            });
        }
    </script>
</body>
</html>

404.jsp

404错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>自定义404页面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <img src="/images/404.png"/>
</body>
</html>

项目点评 ( 0 )

你可以在登录后,发表评论

搜索帮助