包结构如下:

springboot mybatisplus 日志级别 mybatis日志logback_spring

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(50) DEFAULT NULL,

`password` varchar(32) DEFAULT NULL,

`age` int(11) DEFAULT NULL,

`phone` varchar(32) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;



-- ----------------------------

-- Records of user

-- ----------------------------

INSERT INTO `user` VALUES ('1', '张三', '123456', '23', '15094037891');

INSERT INTO `user` VALUES ('3', '李四', '123456', '24', '1509403791');

INSERT INTO `user` VALUES ('5', '赵六', '12345', '34', '15094037891');

INSERT INTO `user` VALUES ('8', '2323', '123456', '445', '44');

 

1.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>testSpringBoot</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>

<!--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>

2.logback.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>

3.application.properties

#web项目名称

server.contextPath=/myweb

#配置freemaker

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

spring.http.encoding.force=true

4.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

5.springboot启动类

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);

}



}

6.实体类

package com.niugang.entity;



public class User {

private int 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 int getId() {

return id;

}



public void setId(int 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;

}



}

7.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.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="queryList" resultMap="BaseResultMap" parameterType="com.niugang.entity.User">

select

<include refid="Base_Column_List" />

from user

<include refid="queryCondition" />

</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>



</mapper>

8.dao层

package com.niugang.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.niugang.entity.User;

@Repository

public interface UserDao {

List<User> queryList(User user);

User get(Integer id);

void save(User user);

void delete(Integer id);

}

9.service层

package com.niugang.service;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;

import com.niugang.dao.UserDao;

import com.niugang.entity.User;

@Service

public class UserService {



private static Logger logger = LoggerFactory.getLogger(UserService.class);

@Resource

private UserDao userDao;

public List<User> queryList(User user) {

logger.info("访问queryList方法");

return userDao.queryList(user);

}

public void save(User user) {

logger.info("访问save方法");

userDao.save(user);

}

public User get(Integer id) {

logger.info("访问get方法");

return userDao.get(id);

}

public void delete(Integer id) {

logger.info("访问delete方法");

userDao.delete(id);

}

}

10.controller层

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 com.niugang.entity.User;

import com.niugang.service.UserService;

@Controller

public class IndexController {

@Resource

private UserService userService;

/**

* 跳转到登录页面

*

* @param map

* @return

*/

@RequestMapping(value = "/login", method = RequestMethod.GET)

public String toLogin(ModelMap map) {

return "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";

}

/**

* 跳转到index页面

*

* @return

*/

@RequestMapping(value = "/index")

public String index(ModelMap map) {

List<User> list = userService.queryList(null);

map.put("users", list);

return "index";

}

/**

* 详情页面

* @param id

* @param map

* @return

*/

@RequestMapping(value = "/detail/{id}")

public String detail(@PathVariable(value="id") Integer id,ModelMap map){

User user = userService.get(id);

map.put("user", user);

return "detail";

}

/**

* 删除

* @param id

* @return

*/

@RequestMapping(value = "/delete/{id}")

public String delete(@PathVariable(value="id") Integer id){

userService.delete(id);

return "redirect:/index";

}

/**

* 跳转到添加页面

* @param map

* @return

*/

@RequestMapping(value = "/save",method = RequestMethod.GET)

public String toSave(ModelMap map) {

return "add";

}

/**

* 保存添加信息

* @param user

* @return

*/

@RequestMapping(value = "/save",method = RequestMethod.POST)

public String save(User user,ModelMap map){

if(StringUtils.isBlank(user.getName())){

map.put("error", "用户名不能为空");

return "add";

}

if(user.getAge()==null){

map.put("error", "非法年龄");

return "add";

}

if(StringUtils.isBlank(user.getPhone())){

map.put("error", "手机号不能为空");

return "add";

}

user.setPassword("123456");

userService.save(user);

return "redirect:/index";

}

}

11.view文件夹中的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>

</html>

index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style type="text/css">

table {

border-collapse: collapse;

margin: 0 auto;

}



table, td, th {

border: 1px solid black;

padding: 15px;

}

</style>

</head>

<body>

<input type="button" value="添加" onclick="add();">

<table>

<thead>

<tr>

<th>用户名</th>

<th>年龄</th>

<th>电话</th>

<th>操作</th>

</tr>



</thead>

<tbody>

<#if users??> <#list users as user>

<tr>

<td>${user.name}</td>

<td>${user.age}</td>

<td>${user.phone}</td>

<td><a href="javascript:void(0)" onclick="edit('${user.id}')" >编辑</a>

<a href="javascript:void(0)" onclick="del('${user.id}')">删除</a>

<a href="javascript:void(0)" onclick="detail('${user.id}')">详情</a>

</td>

</tr>

</#list> </#if>



</tbody>

</table>

<script type="text/javascript">

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(){

window.location.href="save";

}



</script>

</body>

</html>

add.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

</head>

<body>

<h2>添加</h2>

<#if error??>

${error}

</#if>

<form action="save" method='post'>

用户名:<input type="text" name="name"><p>

年龄:<input type="text" name="age"><p>

手机号:<input type="text" name="phone"><p>

<input type="submit" value="提交">

</form>

</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>

页面显示效果如: