9.Spring-Boot之Mybatis-LogBack-Freemarker

包结构如下:

9.Spring-Boot之Mybatis-LogBack-Freemarker_第1张图片


初始化SQL
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.0modelVersion>



<groupId>springbootgroupId>

<artifactId>testSpringBootartifactId>

<version>0.0.1-SNAPSHOTversion>

<packaging>warpackaging>

<name>testSpringBootname>

<url>http://maven.apache.orgurl>

<properties>

<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

properties>



<parent>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-parentartifactId>

<version>1.5.2.RELEASEversion>

<relativePath>relativePath>

parent>

<dependencies>

<dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-webartifactId>

dependency>



<dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-jdbcartifactId>

dependency>



<dependency>

<groupId>org.mybatis.spring.bootgroupId>

<artifactId>mybatis-spring-boot-starterartifactId>

<version>1.2.0version>

dependency>



<dependency>

<groupId>mysqlgroupId>

<artifactId>mysql-connector-javaartifactId>

dependency>



<dependency>

<groupId>com.alibabagroupId>

<artifactId>druidartifactId>

<version>1.0.25version>

dependency>

<dependency>

<groupId>org.apache.commonsgroupId>

<artifactId>commons-lang3artifactId>

<version>3.2version>

dependency>



<dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-freemarkerartifactId>

dependency>



<dependency>

<groupId>com.alibabagroupId>

<artifactId>fastjsonartifactId>

<version>1.2.44version>

dependency>



<dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-testartifactId>

dependency>

<dependency>

<groupId>junitgroupId>

<artifactId>junitartifactId>

<scope>testscope>

dependency>

dependencies>



<build>

<plugins>

<plugin>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-maven-pluginartifactId>

plugin>

plugins>

<pluginManagement>

<plugins>

<plugin>



<artifactId>maven-compiler-pluginartifactId>

<configuration>

<source>1.7source>

<target>1.7target>

configuration>

plugin>



<plugin>

<groupId>org.apache.tomcat.mavengroupId>

<artifactId>tomcat7-maven-pluginartifactId>

<version>2.2version>

plugin>

plugins>

pluginManagement>

build>

project>

 

2.logback.xml\

<configuration>







<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

<encoder>

<pattern>%d %p (%file:%line\)- %m%npattern>



<charset>UTF-8charset>

encoder>

appender>







<appender name="syslog"

class="ch.qos.logback.core.rolling.RollingFileAppender">

<File>d:/springbootlog/springboot.logFile>





<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">





<fileNamePattern>log/springboot.%d.%i.logfileNamePattern>



<maxHistory>30maxHistory>

<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">



<maxFileSize>1KBmaxFileSize>

timeBasedFileNamingAndTriggeringPolicy>

rollingPolicy>

<encoder>



<pattern>

%d %p (%file:%line\)- %m%n

pattern>



<charset>UTF-8charset> 

encoder>

appender>



<root level="info">

<appender-ref ref="STDOUT" />

root>







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

head>

<body>

<h2>spring booth2>

<#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 heretitle>

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

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

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>

 

页面显示效果如:http://blog.csdn.net/niugang0920/article/details/79445700

微信公众号

                           9.Spring-Boot之Mybatis-LogBack-Freemarker_第2张图片

你可能感兴趣的:(9.Spring-Boot之Mybatis-LogBack-Freemarker)