一、创建Mean 项目 这个就不多说了
二、我的spring boot demo 结构 如下:
三、主要的配置文件(application.properties ;pom.xml ; log4j2.xml)
(1、)application.properties 文件
#server
server.port=8888
server.session-timeout=30
server.tomcat.uri-encoding=UTF-8
#datasource
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/studentmanage?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=12
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=150
# 配置获取连接等待超时的时间
spring.datasource.maxWait=0
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
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
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#jap
spring.jpa.properties.hibernate.hbm2ddl.auto=update
#spring.jpa.show-sql=true
#上传大小配置
spring.http.multipart.max-file-size=30Mb
spring.http.multipart.max-request-size=30Mb
#FreeMarker FREEMARKER (FreeMarkerAutoConfiguration)
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.request-context-attribute=request
spring.freemarker.prefer-file-system-access=true
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.number_format=0.##########
spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss
spring.freemarker.settings.classic_compatible=true
spring.freemarker.settings.template_exception_handler=ignore
spring.freemarker.order=1
#log
logging.config=classpath:log4j2.xml
(2 、)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>com.myspringboot</groupId>
<artifactId>myspringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<description>myspringboot</description>
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath></relativePath>
</parent>
<properties>
<alibaba.druid.version>1.0.23</alibaba.druid.version>
<alibaba.fastjson.version>1.2.18</alibaba.fastjson.version>
<mybatis.version>1.1.1</mybatis.version>
<apache.commons-lang.version>3.2.1</apache.commons-lang.version>
<apache.commons-io.version>2.5</apache.commons-io.version>
<thumbnailator.version>0.4.8</thumbnailator.version>
<apache.poi.version>3.14</apache.poi.version>
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- spring-boot的web启动的jar包 -->
<dependencies>
<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>
<!-- Log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--jpa的jar包 ,操作数据库的,类似hibernate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--测试包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
<!--mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 阿里巴巴连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${alibaba.druid.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${alibaba.fastjson.version}</version>
</dependency>
<!--freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons-lang.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${apache.commons-io.version}</version>
</dependency>
<!-- Exceld工具包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${apache.poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache.poi.version}</version>
</dependency>
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>${thumbnailator.version}</version>
</dependency>
</dependencies>
<!--maven的插件 -->
<build>
<finalName>myspringboot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- 配置java版本 不配置的话默认父类配置的是1.6 -->
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<Configuration status="off">
<!-- 日志文件目录和压缩文件 -->
<Properties>
<Property name="fileName">/tmp/logs</Property>
<Property name="fileGz">/tmp/logs/7z</Property>
</Properties>
<Appenders>
<!--这个输出控制台的配置 -->
<Console name="console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="NEUTRAL" />
<!--输出日志的格式 -->
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} %L %M - %msg%xEx%n" />
</Console>
<!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
<RollingRandomAccessFile name="rollingInfoFile" fileName="${fileName}/springboot-info.log" immediateFlush="false"
filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.springboot-info.gz">
<PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} [%t] %-5level %logger{36} %L %M - %msg%xEx%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="6" modulate="true" />
<SizeBasedTriggeringPolicy size="50 MB"/>
</Policies>
<Filters>
<!-- 只记录info级别信息 -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
</Filters>
<!-- 指定每天的最大压缩包个数,默认7个,超过了会覆盖之前的 -->
<DefaultRolloverStrategy max="50"/>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="rollingErrorFile" fileName="${fileName}/springboot-error.log" immediateFlush="false"
filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.springboot-error.gz">
<PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} [%t] %-5level %logger{36} %L %M - %msg%xEx%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="6" modulate="true" />
<SizeBasedTriggeringPolicy size="50 MB"/>
</Policies>
<Filters>
<!-- 只记录error级别信息 -->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" />
</Filters>
<!-- 指定每天的最大压缩包个数,默认7个,超过了会覆盖之前的 -->
<DefaultRolloverStrategy max="50"/>
</RollingRandomAccessFile>
<!--
<JDBC name="databaseAppender" tableName="sys_log">
<ConnectionFactory class="com.blog.config.ConnectionFactory" method="getDatabaseConnection" />
<Column name="date" isEventTimestamp="true"/>
<Column name="file" pattern="%file" />
<Column name="line" pattern="%line" />
<Column name="thread" pattern="%thread" />
<Column name="level" pattern="%level" />
<Column name="message" pattern="%message"/>
</JDBC>
-->
</Appenders>
<Loggers>
<!-- 全局配置,默认所有的Logger都继承此配置 -->
<AsyncRoot level="info" additivity="false">
<AppenderRef ref="console"/>
<AppenderRef ref="rollingInfoFile"/>
<AppenderRef ref="rollingErrorFile"/>
<!--
<AppenderRef ref="databaseAppender" level="warn" />
-->
</AsyncRoot>
</Loggers>
</Configuration>
(4、程序主入口)
package com.myspringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
* @ClassName: Application
* @Description:项目启动入口
*/
//@EnableCaching //缓存
//@EnableScheduling //定时任务
//@EnableAsync //异步任务
@SpringBootApplication // 项目启动
//@ComponentScan("com.myspringboot")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(this.getClass());
}
}
(5、)控制器
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.myspringboot.model.StudentBasis;
import com.myspringboot.service.StudentBasisService;
@Controller
@RequestMapping(value = "/")
@ResponseBody
public class StudentController {
@Autowired
private StudentBasisService studentService;
@RequestMapping(value = "Student/index.html", method = RequestMethod.GET)
public ModelAndView getStudentIndex(HttpServletRequest request) throws Exception {
ModelAndView mv = new ModelAndView("/student/index");
List<StudentBasis> list = new ArrayList<StudentBasis>();
Map<String, Object> whereMap = new HashMap<String, Object>();
list = studentService.getList(whereMap);
System.out.println("获取列表成功!");
mv.addObject("studentlist", list);
return mv;
}
}
(6、)前台页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<#assign boot = basePath >
<html>
<head>
<title>学生列表</title>
<base href="${boot}/" />
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link type="text/css" rel="stylesheet" href="${boot}/public/css/base.css" />
<link type="text/css" rel="stylesheet" href="${boot}/public/css/master.css" />
<script type="text/javascript" language="javascript" src="${boot}/public/js/jquery-2.2.1.min.js"></script>
</head>
<body>
<table class="week_pro">
<tr>
<th>学生学号</th>
<th>学生姓名</th>
<th>手机号码</th>
<th>电子邮件</th>
<th style="width: 80px;">性别</th>
<th style="width: 120px;">操作</th>
</tr>
<#if (studentlist?? && studentlist?size>0)>
<#list studentlist as data>
<tr>
<td>${data.studentcode}</td>
<td>${data.studentname}</td>
<td>${data.mobile}</td>
<td>${data.email}</td>
<td></td>
<td><a class="btn_link" id='${data.id}'>修改</a>
</td>
</tr>
</#list>
</#if>
</table>
</body>
</html>
(7、)如果在前台页面 要想与jsp 那样获取
request.getContextPath() 的效果
需要重新定义 拦截器类和注册类:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 拦截器类
* @author Michael
*
*/
public class CommonInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
throws Exception {
String path = httpServletRequest.getContextPath();
String scheme = httpServletRequest.getScheme();
String serverName = httpServletRequest.getServerName();
int port = httpServletRequest.getServerPort();
String basePath = scheme + "://" + serverName + ":" + port + path;
httpServletRequest.setAttribute("basePath", basePath);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
注册类:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 注册类
* @author Michael
*
*/
@Configuration
public class CommonInterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**");
}
}
前台页面引用如下: