當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot和FreeMarker整合
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot和FreeMarker整合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
- 使用工具
- 環(huán)境搭建
- 代碼示例
- java目錄
- WebLogAspect.java
- DruidDBConfig.java
- UserMapper.java
- User.java
- UserServiceImpl.java
- IUserService.java
- UserController.java
- App.java
- resources目錄
- application.properties 配置
- log4j.properties 配置
- application.yml 配置
- UserMapper.xml
- list.ftl
- pom.xml配置
- 效果展示
使用工具
IDEA2018.2 MySQL5.6 JDK1.8
環(huán)境搭建
代碼示例
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 // 使用@Aspect注解聲明一個(gè)切面 @Component //配置bean public class WebLogAspect {private Logger logger = Logger.getLogger(getClass());@Pointcut("execution(public * net.zjitc.web.controller..*.*(..))")public void webLog() {}@Before("webLog()")public void doBefore(JoinPoint joinPoint) throws Throwable {// 接收到請(qǐng)求,記錄請(qǐng)求內(nèi)容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();// 記錄下請(qǐng)求內(nèi)容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));}}@AfterReturning(returning = "ret", pointcut = "webLog()")public void doAfterReturning(Object ret) throws Throwable {logger.info("---------------response----------------");// 處理完請(qǐng)求,返回內(nèi)容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;@Configuration public class DruidDBConfig {private Logger logger = Logger.getLogger(DruidDBConfig.class);@Value("${spring.datasource.url}")private String dbUrl;@Value("${spring.datasource.username}")private String username;@Value("${spring.datasource.password}")private String password;@Value("${spring.datasource.driverClassName}")private String driverClassName;@Value("${spring.datasource.initialSize}")private int initialSize;@Value("${spring.datasource.minIdle}")private int minIdle;@Value("${spring.datasource.maxActive}")private int maxActive;@Value("${spring.datasource.maxWait}")private int maxWait;@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")private int timeBetweenEvictionRunsMillis;@Value("${spring.datasource.minEvictableIdleTimeMillis}")private int minEvictableIdleTimeMillis;@Value("${spring.datasource.validationQuery}")private String validationQuery;@Value("${spring.datasource.testWhileIdle}")private boolean testWhileIdle;@Value("${spring.datasource.testOnBorrow}")private boolean testOnBorrow;@Value("${spring.datasource.testOnReturn}")private boolean testOnReturn;@Value("${spring.datasource.poolPreparedStatements}")private boolean poolPreparedStatements;@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")private int maxPoolPreparedStatementPerConnectionSize;@Value("${spring.datasource.filters}")private String filters;@Value("{spring.datasource.connectionProperties}")private String connectionProperties;@Bean //聲明其為Bean實(shí)例@Primary //在同樣的DataSource中,首先使用被標(biāo)注的DataSourcepublic DataSource dataSource(){DruidDataSource datasource = new DruidDataSource();datasource.setUrl(this.dbUrl);datasource.setUsername(username);datasource.setPassword(password);datasource.setDriverClassName(driverClassName);//configurationdatasource.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 //service組件 @Transactional public class UserServiceImpl implements IUserService {@Autowired // 自動(dòng)注入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//相當(dāng)于聲明Controller - 提共restful 風(fēng)格 控制器 @RequestMapping("user") public class UserController {@Autowiredprivate IUserService userService;@RequestMapping("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!**/@EnableAutoConfiguration //自動(dòng)配置,不需要寫spring的配置文件 //@ComponentScan(basePackages = {"net.zjitc.datasource","net.zjitc.test1","net.zjitc.test2","net.zjitc.web"}) //還可以這樣寫 @ComponentScan(basePackages = "net.zjitc") @MapperScan(basePackages = "net.zjitc.mapper") public class App {public static void main( String[] args ){//啟動(dòng)springboot項(xiàng)目SpringApplication.run(App.class, args);} // 啟動(dòng)訪問網(wǎng)址: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=requestlog4j.properties 配置
log4j.appender.File.File = 自己設(shè)置緩存地址
info.log 為文件名和文件后綴格式
application.yml 配置
# 注意冒號(hào)后的只能用空格,不能用tab server: # 修改端口號(hào)port: 8080 # 修改路徑context-path: /testUserMapper.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><!--阿里巴巴數(shù)據(jù)庫連接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.25</version></dependency><!-- 數(shù)據(jù)庫驅(qū)動(dòng) --><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事務(wù)依賴 jta 管理多個(gè)數(shù)據(jù)源的事務(wù)--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jta-atomikos</artifactId></dependency><!--排除springboot自帶的logging 日志--><!-- 去除springboot的logging,添加log4j,因?yàn)樽詭У膌ogging不啟效果--><!-- 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><!--重新導(dǎo)入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>效果展示
總結(jié)
以上是生活随笔為你收集整理的SpringBoot和FreeMarker整合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python调用PyAutoGUI模块
- 下一篇: spring框架实现一个学生管理系统