目录
- java目录
- WebLogAspect.java
- DruidDBConfig.java
- UserMapper.java
- User.java
- UserServiceImpl.java
- IUserService.java
- UserController.java
- App.java
- application.properties 配置
- log4j.properties 配置
- application.yml 配置
- UserMapper.xml
- list.ftl
- 效果展示
使用工具
IDEA2018.2 MySQL5.6 JDK1.8
环境搭建
代码示例
java目录
WebLogAspect.java
package net.zjitc.aspect;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/30 21:14
* @Version 1.0
**/
// 使用@Aspect注解声明一个切面
//配置bean
public class WebLogAspect {
private Logger logger = Logger.getLogger(getClass());
("execution(public * net.zjitc.web.controller..*.*(..))")
public void webLog() {
}
("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("---------------request----------------");
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
logger.info("name:" + name + "value" + request.getParameter(name));
}
}
(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
logger.info("---------------response----------------");
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
}
}
DruidDBConfig.java
package net.zjitc.dbconfig;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/31 10:43
* @Version 1.0
**/
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
public class DruidDBConfig {
private Logger logger = Logger.getLogger(DruidDBConfig.class);
("${spring.datasource.url}")
private String dbUrl;
("${spring.datasource.username}")
private String username;
("${spring.datasource.password}")
private String password;
("${spring.datasource.driverClassName}")
private String driverClassName;
("${spring.datasource.initialSize}")
private int initialSize;
("${spring.datasource.minIdle}")
private int minIdle;
("${spring.datasource.maxActive}")
private int maxActive;
("${spring.datasource.maxWait}")
private int maxWait;
("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
("${spring.datasource.validationQuery}")
private String validationQuery;
("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
("${spring.datasource.filters}")
private String filters;
("{spring.datasource.connectionProperties}")
private String connectionProperties;
//声明其为Bean实例
//在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
UserMapper.java
package net.zjitc.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/30 10:55
* @Version 1.0
**/
public interface UserMapper {
}
User.java
package net.zjitc.model;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/29 18:37
* @Version 1.0
**/
public class User {
}
UserServiceImpl.java
package net.zjitc.service.impl;
import net.zjitc.mapper.UserMapper;
import net.zjitc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/29 23:55
* @Version 1.0
**/
//service组件
public class UserServiceImpl implements IUserService {
// 自动注入
private UserMapper userMapper;
}
IUserService.java
package net.zjitc.service;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/29 23:55
* @Version 1.0
**/
public interface IUserService {
}
UserController.java
package net.zjitc.web.controller;
import net.zjitc.service.IUserService;
import net.zjitc.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author ꧁ʚVVcatɞ꧂
* @Date 2019/8/29 18:40
* @Version 1.0
*
**/
//相当于声明Controller - 提共restful 风格 控制器
("user")
public class UserController {
private IUserService userService;
("login")
public String login(){
return "user/list";
}
}
App.java
package net.zjitc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
/**
* Hello world!
*
*/
//自动配置,不需要写spring的配置文件
//@ComponentScan(basePackages = {"net.zjitc.datasource","net.zjitc.test1","net.zjitc.test2","net.zjitc.web"}) //还可以这样写
(basePackages = "net.zjitc")
(basePackages = "net.zjitc.mapper")
public class App
{
public static void main( String[] args )
{
//启动springboot项目
SpringApplication.run(App.class, args);
}
// 启动访问网址:http://localhost:8080/test/user/login
}
resources目录
application.properties 配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#spring.freemarker.suffix=.ftl
#spring.freemarker.templateEncoding=UTF-8
#spring.freemarker.templateLoaderPath=classpath:/templates/
#spring.freemarker.content-type=text/html
spring.freemarker.request-context-attribute=request
log4j.properties 配置
log4j.appender.File.File = 自己设置缓存地址
info.log 为文件名和文件后缀格式
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
#自己设置缓存地址
log4j.appender.File.File = E:/JAVA/JAVAEE/info.log
#设置文件的缓存大小
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n
application.yml 配置
# 注意冒号后的只能用空格,不能用tab
server:
# 修改端口号
port: 8080
# 修改路径
context-path: /test
UserMapper.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="net.zjitc.mapper.UserMapper" >
</mapper>
list.ftl
<!DOCTYPE html>
<!--
*@Author ꧁ʚVVcatɞ꧂
*Date 2019/8/29 22:14
-->
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
Hello World!!!
</table>
</body>
</html>
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>net.zjitc</groupId>
<artifactId>Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Demo</name>
<!--spring boot 父依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring boot配置web的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- mybaties -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--阿里巴巴数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.25</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加jta事务依赖 jta 管理多个数据源的事务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
<!--排除springboot自带的logging 日志-->
<!-- 去除springboot的logging,添加log4j,因为自带的logging不启效果-->
<!-- springboot下的Log4j的版本最新1.3.8,如果你的springboot的parent版本过高,那在在添加log4j自己版本-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--重新导入log4j-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
</project>
效果展示