三种启动方式:
1,run启动类
2,命令行进入项目所在路径,mvn spring-boot:run
3,进入项目路径,先mvn install,接着cd target目录查看,会多出一个girl-0.0.1-SNAPSHOT.jar文件。然后java -jar girl-0.0.1-SNAPSHOT.jar启动这个项目。
yml配置:
注意:如果所有配置写在application.yml里,那么,对后面两个配置文件都起作用。
application.yml:
#指定项目使用application-dev.yml配置文件
spring:
profiles:
active: dev
application-dev.yml:
#开发环境使用的配置文件
server:
port: 8080
girl:
cupSize: b
age: 18
application-prod.yml:
#生产环境使用的配置文件
server:
port: 8090
girl:
cupSize: f
age: 18
如何使生产环境的配置文件也起动生效呢,命令行进入项目路径,mvn install,接着cd target目录,然后使用:
java -jar girl-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
OK了,浏览器8080端口8090端口都能访问了。
注解:
//获取URL里的参数值
@RequestMapping("/{id}")
public String index(@PathVariable Integer id){
return "id:"+id;
}
//这个是获取URL请求参数属性的值,注解括号的id与参数属性一致
@RequestMapping("/")
public String index2(
@RequestParam(value="id",required=false,defaultValue="0") Integer age){
return "id:"+age;
}
//这两个注解效果一样
// @RequestMapping(value = "/",method = RequestMethod.POST)
@PostMapping(value = "/")
SpringBoot使用JPA:
定义一个类,加上如下注解
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
private String cupSize;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Girl() {
}
}
配置信息加上JPA,ddl_auto:有很多参数,create是每次启动项目都会删掉表数据。
spring:
profiles:
active: dev
#======================================数据库配置===========================================#
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: wjb
#=================================JPA配置=================================================#
jpa:
hibernate:
ddl-auto: create
show-sql: true
运行项目数据库就会新建一张girl表,有id,cupSize,age三个字段。
springboot使用拦截器:
1,先写一个拦截器类,实现HandlerInterceptor接口:
package com.wjb.interceptor;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* Created by wjb on 2017/3/28.
*另一种方法是实现WebRequestInterceptor接口,两种方式方法各不一样
*/
public class TestInterceptor implements HandlerInterceptor {
private final static Logger logger = Logger.getLogger(TestInterceptor.class);
/**
* 如果返回值是false,请求将被终止,反之继续。
* Object表示被拦截请求的对象。
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
/*拦截器也能设置编码,这点和过滤器很相似*/
httpServletRequest.setCharacterEncoding("utf-8");
logger.info("进入拦截器====preHandle");
return true;
}
/**
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param modelAndView
* @throws Exception
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
modelAndView.setViewName("/index.html");
logger.info("进入拦截器====postHandle");
}
/**
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @throws Exception
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
logger.info("进入拦截器====afterCompletion");
}
}
2,配置拦截器:
package com.wjb.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by wjb on 2017/3/28.
*
* 过滤器filter依赖于servlet容器,基于回调函数,过滤范围较大
*
* 拦截器interceptor依赖于框架容器,基于反射机制,只过滤请求
*/
@Configuration //标注此文件为一个配置项,spring boot才会扫描到该配置。该注解类似于之前使用xml进行配置
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
// registry.addInterceptor(new TestInterceptor2()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
springboot使用aop:
package com.wjb.ascept;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* Created by wjb on 2017/3/22.
*
* 集成AOP,实现日志输出,先添加依赖
*
*
*/
@Aspect //引入AOP
@Component //让Spring集成AOP
public class HttpAspect {
/**
* Spring自带的Logger日志(和log4j有点区别)
*/
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
/**
* 切入点
*/
@Pointcut("execution(public * com.wjb.controller.GirlController.*(..))")
public void log(){
}
/**
* 在指定方法之前执行以下方法
*/
@Before("log()")
public void beforeLog(JoinPoint joinPoint){
logger.info("===========aop开始===========");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("url={}",request.getRequestURI());
logger.info("method={}",request.getMethod());
logger.info("ip={}",request.getRemoteAddr());
//类方法
logger.info("classMethod={}",joinPoint.getSignature()+","+joinPoint.getTarget());
//参数
logger.info("args={}",joinPoint.getArgs());
}
/**
* 在指定方法之后执行以下方法
*/
@After("log()")
public void afterLog(){
logger.info("===========aop结束=============");
}
}
application.yml文件:
spring:
#====================================thymeleaf模板===========================#
thymeleaf:
mode: HTML5
cache: false
content-type: text/html
messages:
encoding: UTF-8
#====================================jdbc配置================================#
datasource:
url: jdbc:mysql://127.0.0.1:3306/springmvcdb
username: root
password: wjb
dbcp2:
driver-class-name: com.mysql.jdbc.Driver
max-active: 20
initial-size: 0
max-idle: 30
min-idle: 1
max-wait: 60000
type: com.alibaba.druid.pool.DruidDataSource
#===================================文件上传配置================================#
http:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB
#===================================项目热布置,依赖插件试过都不行。Ctrl+F9(生成项目),Ctrl+Shift+F9(编译项目)完美解决=================================#
# devtools:
# restart:
# exclude: templates/**,static/**
# enabled: false
#===================================mybatis配置===============================#
mybatis:
mapper-locations: classpath:mapper/*/*.xml
configuration:
map-underscore-to-camel-case: true
callSettersOnNulls: true
#==================================================redis配置========================================#
redis:
database: 0
host: 120.25.176.86
port: 6379
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 0
password: go2hell
网友评论