• 2.基于Spring-Boot的代码规范实例


    包结构maven

    src/main/java  -----存放java文件

       com.niugang.

                   aop

                        ------  ControllerAop.java  web层aop

                   bean

                        ------  UserQuery.java       mybatis查询实体

                  controller

                          ------ IndexController.java

                   dao

                       ------ UserDao.java

                   entity

                       ------ User.java

                   exception

                        ------ CheckException.java 自定义异常

                   service

                        ------ UserService.java

                   utils

                         ------ CodeConstant.java  常量类

                         ------ Page.java 分页对象,封装常用具体参数

                         ------ PageResultBean.java  web层返回统一的分页查询对象

                         ------ Result.java                  web层返回标示性接口

                         ------ ResultBean.java         web层返回统一对象

                  Application.java ---springboot启动类

       src/main/test -----存放测试类文件

       src/main/resources-----存放配置文件

                        mapper mybatis xml文件

                              User.xml 

                        static    静态文件

                              ----script   js文件

                              ----themes  cs文件

                         tempaltes    

                                 ----error

                                       error.html 覆盖springboot默认的错误文件

                                ----view

                                       add.html

                                      detail.html

                                      index.html

                                      login.html

                  application-jdbc.properties

                  application.properties

                  logback-boot.xml   日志

    pom.xml

    <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>springboot</groupId>
    <artifactId>testSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>2_SpringBoot_FreemarkerMyBatis</name>
    <url>http://maven.apache.org</url>
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!-- 继承父包 -->
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath></relativePath>
    </parent>
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--jdbc -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- Spring Boot Mybatis 依赖 -->
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
    </dependency>
    <!--mysql驱动 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--连接池 -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.25</version>
    </dependency>
    <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.2</version>
    
    </dependency>
    
                 <!-- freemarker -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <!--alibab json  -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.44</version>
    </dependency>
    <!--单元测试 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
    </dependency>
    </dependencies>
    <!--maven的插件 -->
    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    <pluginManagement>
    <plugins>
    <plugin>
    <!-- 配置java版本 不配置的话默认父类配置的是1.6 -->
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
    <source>1.7</source>
    <target>1.7</target>
    </configuration>
    </plugin>
    <!-- 配置Tomcat插件 -->
    <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
    </plugin>
    </plugins>
    </pluginManagement>
    </build>
    </project>

    application-jdbc.properties

    # 驱动配置信息
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8 
    spring.datasource.username = root
    spring.datasource.password = 123456
    
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    
    #连接池的配置信息
    ## 初始化大小,最小,最大
    spring.druid.initialSize=5
    spring.druid.minIdle=5
    spring.druid.maxActive=20
    ## 配置获取连接等待超时的时间
    spring.druid.maxWait=60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    spring.druid.timeBetweenEvictionRunsMillis=60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    spring.druid.minEvictableIdleTimeMillis=300000
    spring.druid.validationQuery=SELECT 1 FROM DUAL
    spring.druid.testWhileIdle=true
    spring.druid.testOnBorrow=false
    spring.druid.testOnReturn=false
    spring.druid.poolPreparedStatements=true
    spring.druid.maxPoolPreparedStatementPerConnectionSize=20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    spring.druid.filters=stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    spring.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

    application.properties

    #web项目名称
    server.contextPath=/myweb
    #配置freemaker
    #模板地址默认从classpath:templates下面加载
    #spring.freemarker.template-loader-path=/WEB-INF/view
    spring.freemarker.cache=false
    spring.freemarker.charset=UTF-8
    spring.freemarker.check-template-location=true
    spring.freemarker.content-type=text/html
    spring.freemarker.expose-request-attributes=true
    spring.freemarker.expose-session-attributes=true
    spring.freemarker.request-context-attribute=request
    
    spring.freemarker.suffix=.html
    
    #引入jdbc相关配置
    spring.profiles.active=jdbc
    #mybatis.config = mybatis 配置文件名称
    #mybatis.mapperLocations = mapper xml 文件地址
    #mybatis.typeAliasesPackage = 实体类包路径
    #mybatis.typeHandlersPackage = type handlers 处理器包路径
    #mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
    #mybatis.executorType = 执行模式。默认是 SIMPLE
    ## Mybatis 配置
    mybatis.typeAliasesPackage=com.niugang.entity
    mybatis.mapperLocations=classpath:mapper/*.xml
    #logback配置
    #=====================================  log  =============================  
    logging.config=classpath:logback-boot.xml
    #修改默认HTTP编码,之前是在web.xml中过滤的
    spring.http.enconding.charset=UTF-8

    logback-boot.xml  

    <configuration>      
        <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->      
        <!-- appender是configuration的子节点,是负责写日志的组件。 -->  
        <!-- ConsoleAppender:把日志输出到控制台 -->  
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">      
            <encoder>      
                <pattern>%d %p (%file:%line)- %m%n</pattern>    
                <!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 -->  
                <charset>UTF-8</charset>     
            </encoder>      
        </appender>      
        <!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->  
        <!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->  
        <!--             2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->  
        <appender name="syslog"      
            class="ch.qos.logback.core.rolling.RollingFileAppender">      
            <File>d:/springbootlog/springboot.log</File>      
            <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->  
            <!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->  
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">      
                <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->  
                <!-- 文件名:log/sys.2017-12-05.0.log -->  
    
                <fileNamePattern>log/springboot.%d.%i.log</fileNamePattern>   
    
     <!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->   
                <maxHistory>30</maxHistory>     
                <timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">      
                    <!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->    
                    <maxFileSize>1KB</maxFileSize>      
                </timeBasedFileNamingAndTriggeringPolicy>      
            </rollingPolicy>      
            <encoder>      
                <!-- pattern节点,用来设置日志的输入格式 -->  
                <pattern>      
                    %d %p (%file:%line)- %m%n    
                </pattern>      
                <!-- 记录日志的编码 -->  
                <charset>UTF-8</charset> <!-- 此处设置字符集 -->     
            </encoder>      
        </appender>      
        <!-- 控制台输出日志级别 -->  
        <root level="info">      
            <appender-ref ref="STDOUT" />      
        </root>      
        <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->  
        <!-- com.niugang为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->  
        <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  -->  
        <logger name="com.niugang" level="DEBUG">      
            <appender-ref ref="syslog" />      
        </logger>      
    </configuration>   
     

    ControllerAop.java

    package com.niugang.aop;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    import com.niugang.exception.CheckException;
    import com.niugang.utils.CodeConstant;
    import com.niugang.utils.PageResultBean;
    import com.niugang.utils.Result;
    import com.niugang.utils.ResultBean;
    @Aspect
    @Component
    public class ControllerAop {
    private Logger logger = LoggerFactory.getLogger(ControllerAop.class);
    @Around("execution(public * com.niugang.controller..*.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
    
    long startTime = System.currentTimeMillis();
    
                Result result;
    try {
    Object proceed = pjp.proceed();
    // 对于页面的处理
    if (proceed instanceof String) {
    logger.info("result request page address");
    return proceed;
    } else if (proceed instanceof ResultBean) { //对于查询单个对象
    result = (ResultBean<?>) proceed;
    } else {
    result = (PageResultBean<?>) proceed; //对于分页查询
    }
    // 如果需要打印入参,可以从这里取出打印
    // Object[] args = pjp.getArgs();
    // 本次操作用时(毫秒)
    long elapsedTime = System.currentTimeMillis() - startTime;
    logger.info("[{}] use time: {}", pjp.getSignature(), elapsedTime);
    } catch (Throwable e) {
    result = handlerException(pjp, e);
    }
    return result;
    
    }
    
             @SuppressWarnings("rawtypes")
    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
            //TODO  pjp返回类型待判断
    ResultBean<?> result = new ResultBean();
    // 已知异常【注意:已知异常不要打印堆栈,否则会干扰日志】
    // 校验出错,参数非法
    if (e instanceof CheckException || e instanceof IllegalArgumentException) {
    result.setResultMessage(e.getLocalizedMessage());
    result.setResultCode(CodeConstant.CHECK_FAIL);
    } else {
    logger.error(pjp.getSignature() + " error ", e);
    // TODO 未知的异常,应该格外注意,可以发送邮件通知等
    result.setResultMessage("未知异常");
    result.setResultCode(CodeConstant.UNKNOWN_EXCEPTION);
    }
    return result;
    }
    
    }

    UserQuery.java

    package com.niugang.bean;
    import com.niugang.entity.User;
    import com.niugang.utils.CodeConstant;
    
    /**
     * 封装实体类 查询对象
     * @author niugang
     *
     */
    public class UserQuery extends User {
    
    
    /**
    * 页码
    */
    private int pageNumber = CodeConstant.DEFAULT_PAGE_NUMBER;
    /**
    * 页面大小
    */
    private int pageSize = CodeConstant.DEFAULT_PAGE_SIZE;
    /**
    
    * mysql分页查询 limit startRows,pageSize;
    
          */
    private int startRows;
    public int getPageNumber() {
    return pageNumber;
    }
    public void setPageNumber(int pageNumber) {
    this.pageNumber = pageNumber;
    }
    public int getPageSize() {
    return pageSize;
    }
    public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
    }
    public int getStartRows() {
    return (pageNumber-1)*pageSize;
    }
    public void setStartRows(int startRows) {
    this.startRows = startRows;
    }
    }

    IndexController.java

    package com.niugang.controller;
    import java.util.List;
    import javax.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.niugang.bean.UserQuery;
    import com.niugang.entity.User;
    import com.niugang.service.UserService;
    import com.niugang.utils.PageResultBean;
    import com.niugang.utils.ResultBean;
    /**
     * 
     * @author niugang spring boot helloWrold
    
     */
    
    public class IndexController {
    @Resource
    private UserService userService;
    
    
    /**
    * 跳转到登录页面
    * 
    * @param map
    * @return
    */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin(ModelMap map) {
    return "view/login";
    }
    
    
    /**
    * 登录信息校验
    * 
    * @param map
    * @return
    */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(ModelMap map, String name, String password) {
    
    
    if (StringUtils.isNotBlank(name) && !name.equals("admin") && StringUtils.isNotBlank(password)
    && !password.equals("123456")) {
    map.put("errorMessage", "用户名或密码错误");
    return "login";
    }
    
    
    return "redirect:index";
    
    }
    
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String toIndex() {
    return "view/index";
    }
    
    
    /**
    * 分页查询
    * 
    * @return
    */
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    @ResponseBody
    public PageResultBean<User> index(UserQuery query) {
    List<User> list = userService.queryListByPage(query);
    int queryCount = userService.queryCount(query);
    PageResultBean<User> pageResultBean = new PageResultBean<User>();
    pageResultBean.setData(list);
    pageResultBean.setPageNumber(query.getPageNumber());
    pageResultBean.setPageSize(query.getPageSize());
    pageResultBean.setTotalCount(queryCount);
    
    
    return pageResultBean;
    }
    
    
    /**
    * 跳转到详情页面
    * 
    * @return
    */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    
    
    public String toDetail() {
    return "view/detail";
    
    }
    
           /**
    * 详情信息
    * 
    * @param id
    * @param map
    * @return
    */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean<User> detail(@PathVariable(value = "id") Integer id) {
    User user = userService.get(id);
    ResultBean<User> resultBean = new ResultBean<User>();
    resultBean.setData(user);
    return resultBean;
    }
    /**
    * 删除
    * 
    * @param id
    * @return
    */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public ResultBean<User> delete(@PathVariable(value = "id") Integer id) {
    userService.delete(id);
    ResultBean<User> resultBean = new ResultBean<User>();
    return resultBean;
    }
    
         /**
    * 跳转到添加页面
    * 
    * @param map
    * @return
    */
    @RequestMapping(value = "/save", method = RequestMethod.GET)
    public String toSave(ModelMap map) {
    return "view/add";
    }
    
    
    /**
    * 保存添加信息
    * 按照正常的逻辑,添加完用户信息,要将id返回
    * 
    * @param user
    * @return
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean<User> save(User user) {
    userService.save(user);
    ResultBean<User> resultBean = new ResultBean<User>();
    return resultBean;
    }
    
    
    }

    UserDao.java

    package com.niugang.dao;
    import java.util.List;
    import org.springframework.stereotype.Repository;
    import com.niugang.bean.UserQuery;
    import com.niugang.entity.User;
    @Repository
    public interface UserDao {
    List<User> queryListByPage(UserQuery user);
    User get(Integer id);
    void save(User user);
    void delete(Integer id);
    int queryCount(UserQuery user);
    }

    User.java

    package com.niugang.entity;
    public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String phone;
    private String password;
    
    
    public String getPassword() {
    return password;
    }
    
    
    public void setPassword(String password) {
    this.password = password;
    
    }
    
          public Integer getId() {
    return id;
    }
    
    
    public void setId(Integer 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 String getPhone() {
    return phone;
    }
    
    
    public void setPhone(String phone) {
    this.phone = phone;
    }
    
    
    @Override
    public String toString() {
    return "User [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + ", password=" + password
    + "]";
    }
       
    }
    
    CheckException.java 
    
    package com.niugang.exception;
    
    
    /**
     * 检测异常
     * @author niugang
     * 只能继承RuntimeException spring aop只能捕获RuntimeException异常
     *
     */
    public class CheckException extends RuntimeException {
    
    
    private static final long serialVersionUID = 1L;
    
    
    public CheckException() {
    }
    
    
    public CheckException(String message) {
    super(message);
    }
    
    
    public CheckException(Throwable cause) {
    super(cause);
    }
    
    
    public CheckException(String message, Throwable cause) {
    super(message, cause);
    }
    
    
    public CheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(message, cause, enableSuppression, writableStackTrace);
    }
    
    }

    UserService.java

    package com.niugang.service;
    
    
    import java.util.List;
    
    
    import javax.annotation.Resource;
    
    
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import com.niugang.bean.UserQuery;
    import com.niugang.dao.UserDao;
    import com.niugang.entity.User;
    import com.niugang.exception.CheckException;
    
    
    @Service
    public class UserService {
    
    
    private static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Resource
    private UserDao userDao;
    
    
    public List<User> queryListByPage(UserQuery user) {
    logger.info("access queryListByPage method params is:{}", user.toString());
    return userDao.queryListByPage(user);
    
    
    
    }
    
    @Transactional
    public void save(User user) {
    logger.info("access get method params is:{}", user.toString());
    if (StringUtils.isBlank(user.getName())) {
    throw new CheckException("用户名不能为空");
    }
    if (user.getAge() == null) {
    throw new CheckException("年龄不能为空");
    }
    if (StringUtils.isBlank(user.getPhone())) {
    throw new CheckException("电话不能为空");
    }
    user.setPassword("123456");
    userDao.save(user);
    //为了验证事务
    //throw new CheckException("添加数据错误");
    
    
    }
    
    
    public User get(Integer id) {
    logger.info("access get method param is:{}", id);
    return userDao.get(id);
    }
    
    
    public void delete(Integer id) {
    logger.info("access delete method param is:{}", id);
    userDao.delete(id);
    }
    
    
    public int queryCount(UserQuery user) {
    logger.info("access queryCount method param is:{}", user.toString());
    return userDao.queryCount(user);
    }
    
    
    }

    CodeConstant.java

    package com.niugang.utils;
    /**
     * 常量表
     * @author niugang
     *
     */
    public class CodeConstant {
       /**
        * 没有登录
        */
    public static final int NO_LOGIN = -1;
        /**
         * 成功
         */
    public static final int SUCCESS = 0;
        /**
         * 检查
         */
    public static final int CHECK_FAIL = 1;
        /**
         * 没有权限
         */
    public static final int NO_PERMISSION = 2;
        /**
         * 位置异常
         */
    public static final int UNKNOWN_EXCEPTION = -99;
    /**
    * 默认页码
    */
    public static final int  DEFAULT_PAGE_NUMBER=1;
    /**
    * 默认页面大小
    */
    public static final int  DEFAULT_PAGE_SIZE=5;
    }

    Page.java

    package com.niugang.utils;
    
    
    /**
     * 页面对象
     * 
     * @author niugang
     *
     */
    public class Page {
    /**
    * 页码
    */
    private int pageNumber = CodeConstant.DEFAULT_PAGE_NUMBER;
    /**
    * 页面大小
    */
    private int pageSize = CodeConstant.DEFAULT_PAGE_SIZE;
    /**
    * 总页数
    */
    private int totalPage;
    
    
    /**
    * 总记录数
    */
    
    private int totalCount;
    
          public int getPageNumber() {
    return pageNumber;
    }
    
    
    public void setPageNumber(int pageNumber) {
    this.pageNumber = pageNumber;
    }
    
    
    public int getPageSize() {
    return pageSize;
    }
    
    
    public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
    }
    
    
    public int getTotalPage() {
    if (totalCount % pageSize == 0) {
    return totalCount / pageSize;
    }
    return totalCount / pageSize + 1;
    }
    
    
    public void setTotalPage(int totalPage) {
    this.totalPage = totalPage;
    }
    
    
    public int getTotalCount() {
    return totalCount;
    }
    
    
    public void setTotalCount(int totalCount) {
    this.totalCount = totalCount;
    }
    
    }

    PageResultBean.java

    package com.niugang.utils;
    import java.io.Serializable;
    import java.util.List;
    
    
    /**
     * controller层返回带分页对象
     * @author niugang
     *
     */
    public class PageResultBean<T> extends Page implements Serializable,Result{
    
    private static final long serialVersionUID = 1L;
    /**
    * 返回的信息
    */
    private String resultMessage = "success";
    /**
    * 返回码
    */
    
    private  Integer resultCode=CodeConstant.SUCCESS;
    
       
    /**
    * 返回的数据
    */
    private List<T> data;
    public PageResultBean() {
    super();
    }
    
    public PageResultBean(String resultMessage, Integer resultCode, List<T> data) {
    super();
    this.resultMessage = resultMessage;
    this.resultCode = resultCode;
    this.data = data;
    }
    
    public String getResultMessage() {
    return resultMessage;
    }
    
    public void setResultMessage(String resultMessage) {
    this.resultMessage = resultMessage;
    }
    public Integer getResultCode() {
    return resultCode;
    }
    
    public void setResultCode(Integer resultCode) {
    this.resultCode = resultCode;
    }
    
    public List<T> getData() {
    return data;
    }
    public void setData(List<T> data) {
    this.data = data;
    }
    
    }
    
    
    
    
    Result.java
    package com.niugang.utils;
    
    
    /**
     * 标示性接口
     * @author niugang
     *
     */
    public interface Result{
    
    
    }

    ResultBean.java

    package com.niugang.utils;
    
    
    import java.io.Serializable;
    /**
     * controller层返回对象
     * @author niugang
     *
     * @param <T>
     */
    public class ResultBean<T> implements Serializable,Result{
    
    private static final long serialVersionUID = 1L;
    /**
    * 放回的信息
    */
    private String resultMessage = "success";
    /**
    * 返回码
    */
    
    private  Integer resultCode=CodeConstant.SUCCESS;
    
          /**
    * 返回的数据
    */
    private T data;
    
    public ResultBean() {
    super();
    }
    public ResultBean(String resultMessage, Integer resultCode, T data) {
    super();
    this.resultMessage = resultMessage;
    this.resultCode = resultCode;
    this.data = data;
    }
    public String getResultMessage() {
    return resultMessage;
    }
    public void setResultMessage(String resultMessage) {
    this.resultMessage = resultMessage;
    }
    public Integer getResultCode() {
    return resultCode;
    }
    public void setResultCode(Integer resultCode) {
    this.resultCode = resultCode;
    }
    public T getData() {
    return data;
    }
    public void setData(T data) {
    this.data = data;
    }
    
    }

    Application.java

    package com.niugang;
    
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    //解决包tomcat冲突
    //@EnableAutoConfiguration(exclude={WebMvcAutoConfiguration.class}) 
    //组件扫描,会自动扫描springboot启动类包及其子包下的注解文件
    //@ComponentScan("com.niugang.controller")
    //springboot注解
    //springboot1.2+之后用@SpringBootApplication替代了三个注解
    @SpringBootApplication
    //mapper 接口类扫描包配置
    @MapperScan(value={"com.niugang.dao"})
    public class Application extends  SpringBootServletInitializer{
    
         public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
    
    
    }

    User.xml

    <?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.niugang.dao.UserDao">
    <resultMap id="BaseResultMap" type="com.niugang.entity.User">
    <result column="id" property="id" />
    <result column="name" property="name" />
    <result column="age" property="age" />
    <result column="phone" property="phone" />
    </resultMap>
    
    
    <!--查询字段 -->
    <sql id="Base_Column_List">
    id, name, age,phone
    </sql>
    <!-- 查询条件 -->
    <sql id="queryCondition">
    <where>
    <if test="id!=null">
    and id=#{id}
    </if>
    <if test="name!=null">
    and name=#{name}
    </if>
    <if test="age!=null">
    and age=#{age}
    </if>
    <if test="phone!=null">
    and phone=#{phone}
    </if>
    </where>
    
    </sql>
    
          <select id="queryListByPage" resultMap="BaseResultMap"
    parameterType="com.niugang.bean.UserQuery">
    select a.* from user a ,(select id from user 
          <where>
    <if test="id!=null">
    and id=#{id}
    </if>
    <if test="name!=null">
    and name=#{name}
    </if>
    <if test="age!=null">
    and age=#{age}
    </if>
    <if test="phone!=null">
    and phone=#{phone}
    </if>
        </where>
    order by id  limit #{startRows},#{pageSize} ) b where a.id=b.id
    
    
    </select>
    
    
    <insert id="save" parameterType="com.niugang.entity.User" >
    insert into user (name,password,age,phone)
    values(#{name},#{password},#{age},#{phone})
    </insert>
    
    
    <delete id="delete" parameterType="int">
    delete from user where id
    =#{id}
    </delete>
    
    
    <select id="get" parameterType="int" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from user
    where id =#{id}
    </select>
     
        <select id="queryCount" parameterType="com.niugang.bean.UserQuery" resultType="int">
         
          select count(*) from user 
            <where>
    <if test="id!=null">
    and id=#{id}
    </if>
    <if test="name!=null">
    and name=#{name}
    </if>
    <if test="age!=null">
    and age=#{age}
    </if>
    <if test="phone!=null">
    and phone=#{phone}
    </if>
        </where>
        </select>
    
    </mapper>

    error.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
         未知异常
    </body>
    
    </html>

    add.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <link rel="stylesheet" type="text/css" href="themes/bootstrap.min.css" />
    <script type="text/javascript" src="script/jquery.min.js"></script>
    <script type="text/javascript" src="script/bootstrap.js"></script>
       <!--layer弹出框-->
        <link rel="stylesheet" href="script/layer/mobile/need/layer.css">
    <script type="text/javascript" src="script/layer/layer.js"></script>
    <style>
       form{
         width:60%;
         margin:0 auto;  
      }
      
    </style>
    <body>
    
    
    <form id="add_form">
    <div class="form-group">
    <label for="name">姓名</label> <input
    type="text" class="form-control" name="name" placeholder="姓名">
    </div>
    <div class="form-group">
    <label for="age">年龄</label> <input
    type="text" class="form-control" name="age"
    placeholder="年龄">
    </div>
    <div class="form-group">
    <label for="phone">电话</label> <input
    type="text" class="form-control" name="phone"
    placeholder="电话">
    </div>
    <!-- <button type="button" id="btn_save" class="btn btn-primary form-control">保存</button> -->
    </form>
    
    </body>
    </html>

    index.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" href="themes/bootstrap.min.css" />
    <script type="text/javascript" src="script/jquery.min.js"></script>
    <script type="text/javascript" src="script/bootstrap.js"></script>
    <!--layer弹出框-->
    <link rel="stylesheet" href="script/layer/mobile/need/layer.css">
    <script type="text/javascript" src="script/layer/layer.js"></script>
    <style type="text/css">
    button {
    margin-left: 15px;
    }
    </style>
    </head>
    <body>
    <button type='button' class='btn btn-info' onclick="add();">添加</button>
    <table class="table table-bordered table-striped"
    style=" 75%; margin: 0 auto">
    <thead>
    <tr>
    <th>用户名</th>
    <th>年龄</th>
    <th>电话</th>
    <th>操作</th>
    </tr>
    
    
    </thead>
    <tbody>
    
    </tbody>
    
    </table>
    
    <nav aria-label="Page navigation" style=" 240px; margin: 0 auto">
    <ul class="pagination">
    <li><a href="#" aria-label="Previous" id="previousPage"> <span
    aria-hidden="true">上一页</span>
    </a></li>
    <li><a href="#" aria-label="Next" id="nextPage"> <span
    aria-hidden="true">下一页</span>
    </a></li>
    <li><input type="hidden" id="pageNumber"><input
    type="hidden" id="totalPage"></li>
    </ul>
    </nav>
    <script type="text/javascript">
    
    function initData(pageNumber) {
    
    $
    .ajax({
    type : "POST",
    url : "index",
    data : {
    "pageNumber" : pageNumber
    },
    dataType : "json",
    success : function(data) {
    if (data.resultCode == 0) {
    var dataList = data.data;
    $("tbody").children().remove();
    if (dataList && dataList.length > 0) {
    for (var i = 0; i < dataList.length; i++) {
    var template = "<tr>";
    template += "<td>" + dataList[i].name
    + "</td>"
    template += "<td>" + dataList[i].age
    + "</td>"
    template += "<td>" + dataList[i].phone
    + "</td>"
    template += "<td><button type='button' class='btn btn-info' >详情</button><button type='button' class='btn btn-warning'>删除</button></td>"
    template += "</tr>"
    $("tbody").append(template);
    }
    
    
    }
    $("#pageNumber").val(data.pageNumber);
    var totalPage = data.totalPage;
    if (totalPage != 0) {
    $("#totalPage").val(totalPage);
    }
    
    
    }
    }
    
    
    });
    
    }
    
                  initData(1);
    function edit(id) {
    alert(id);
    }
    function del(id) {
    var flag = confirm("你确定要删除此选项吗");
    if (flag == true) {
    window.location.href = "delete/" + id;
    }
    }
    function detail(id) {
    window.location.href = "detail/" + id;
    }
    function add() {
    var openIndex=layer.open({
    type : 2, //ifrme层,才能写请求路径
    title : "添加人员",
    resize : false,//不允许拉伸,
    move : false,//不允许拖动
    area : [ '650px', "60%" ],
    maxmin : true,//支持最大化最小化
    btn : [ '保存', '取消' ],
    content : [ 'save', 'no' ], //这里content是一个普通的String
    yes : function(index, layero) {
    var body = layer.getChildFrame("body", index);
    var con = body.find("#add_form").serialize();
    $.ajax({
    type : "POST",
    url : "save",
    data : con,
    dataType : "json",
    success : function(data) {
    if (data.resultCode == 0) {
    $(body.find("#add_form"))[0].reset()
    layer.msg('保存成功', {icon: 4,time:1000,anim: 6});
        //layer.close(openIndex);
    /* layer.alert("保存成功", {
    title : "消息",
    resize : false,
    move : false,
    success:function(){
    layer.close(openIndex);
    }
    }) */
                                    
    } else {
    layer.alert(data.resultMessage, {
    title : "错误信息",
    resize : false,
    move : false
    });
    }
    }
    
    
    });
    
    
    },
    success : function(layero, index) {//弹出层后的成功回调函数
    
    
    }
    });
    }
    $("#nextPage").click(function() {
    var pageNumber = parseInt($("#pageNumber").val());
    var totalPage = parseInt($("#totalPage").val());
    if (pageNumber + 1 > totalPage) {
    $(this).attr("disabled", true);
    layer.msg('已经到尾页啦', {icon: 4,time:1000,anim: 6});
    } else {
    initData(1 + pageNumber);
    $(this).attr("disabled", false);
    }
    
    
    });
    $("#previousPage").click(function() {
    var pageNumber = parseInt($("#pageNumber").val());
    var totalPage = parseInt($("#totalPage").val());
    if (pageNumber - 1 < 1) {
    $(this).attr("disabled", true);
    layer.msg('已经到首页啦', {icon: 4,time:1000,anim: 6});
    } else {
    initData(pageNumber - 1);
    $(this).attr("disabled", false);
    }
    
    
    });
    </script>
    </body>
    </html>

    detail.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
      <h2>详情页面</h2>
      用户名:<input type="text" readonly value="${user.name!''}">
      年龄:<input type="text" readonly value="${user.age!''}">
      电话:<input type="text" readonly value="${user.phone!''}">
    </body>
    </html>

    login.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
           <h2>spring boot</h2>
          <#if errorMessage??> 
             ${errorMessage}
           </#if>
            <form action="login" method='post'>
               用户名:<input type="text" name="name"><p>
                密码:<input type="password" name="password"><p>
                <input type="submit" value="提交">
            </form>
    </body>

    运行结果

    这个错误就是从后天返回的,通过aop统一处理的

           

                                                                                   微信公众号: 

                                                   

                                                                                 JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。 

  • 相关阅读:
    关于litecoin莱特币挖矿、炒作的一点感想
    win7-opengl开发环境的搭建
    基本图形的光栅化算法
    问题:glGenBuffers()函数没有定义怎么办
    maya user guider第一课,一些基本概念
    第一课 opengl简介
    获取0点和24点时间戳的方式
    Yii2框架查询指定字段和获取添加数据的id
    yii2框架安装
    七牛存储图片代码
  • 原文地址:https://www.cnblogs.com/niugang0920/p/12196642.html
Copyright © 2020-2023  润新知