1分钟学会SpringBoot2知识点,让你35岁不再失业(一)
目录
- 1分钟学会SpringBoot2知识点,让你35岁不再失业(一)
- 第一节、快速构建项目
- 第二节、新建多模块和调通第一个hello sprintboot2接口
- 第三节、公司内网情况下构建springboot2项目
- 第四节、配置文件读取
- 1、properties配置文件读取
- 2、yaml配置文件读取
- 第五节、配置文件多环境读取
- 第六节、静态工具类读取配置文件
- 第七节、Springboot2过滤器
- 第八节、Springboot2拦截器
- 第九节、SpringMVC静态资源路径
- 第十节、SpringBoot整合Jsp
- 第十一节、springboot整合thymeleaf
- 第十二节、springboot整合freemarker
第一节、快速构建项目
1、打开IDEA,选择 FILE ---NEW---SPRING Initializr---NEXT
2、GroupId和ArtifactId随便取多创建几次就熟悉了,填写完点击NEXT---NEXT---FINISH---NEWWINDOW,然后一个springboot2项目就创建好了。
第二节、新建多模块和调通第一个hello sprintboot2接口
1、删除新建好的父工程下面的src和.mvn以及mvnw和mvnw.cmd文件
2、打开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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
</project>
3、然后点击项目名—NEW—Module—选择maven—NEXT—给子模块取名—NEXT–Module name修改为和前面取的名字一样—FINISH
4、按照步骤3再来建一个新的Module名字不要取一样
5、建立好以后在父模块的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>device-web</module>
<module>device-service</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.unionpay.ysf</groupId>
<artifactId>device-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>device-parent</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<!--管理web模块-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>device-web</artifactId>
<version>${project.version}</version>
</dependency>
<!--管理service模块-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>device-service</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
6、可以知道我们这里的例子是两个模块名分别是device-web和device-service (名字按照个人风格随便取),然后打开device-web这个子模块的pom.xml引入service模块,因为要依赖service模块如下所示
<?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">
<parent>
<artifactId>device-parent</artifactId>
<groupId>com.unionpay.ysf</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-web</artifactId>
<dependencies>
<!--引入service模块-->
<dependency>
<groupId>com.unionpay.ysf</groupId>
<artifactId>device-service</artifactId>
</dependency>
</dependencies>
</project>
7、然后在device-web模块的src—main—java—右键点击java—NEW—package ,输入包名点击确定。然后新建一个springboot启动入口,因为我们刚才删除了父模块的启动类所以要重新创建一个。如下所示:
package com.yyliu1;
/*
@auther 刘阳洋
@date 2030/4/21 17:41
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[]args){
SpringApplication.run(SpringBootWebApplication.class,args);
System.out.println("启动成功");
}
}
8、然后再在这个包下面新建一个controller文件夹新建一个TestController.java代码如下:
package com.yyliu1.controller;
/*
@auther 刘阳洋
@date 2030/4/21 17:43
*/
import com.unionpay.ysf.service.interfacer.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class TestController {
@Autowired
private UserService userService;
@GetMapping("/test")
public String hello(){
return userService.testService();
}
}
9、点开刚才建的device-service模块,然后在device-service模块的src—main—java—右键点击java—NEW—package ,输入包名点击确定,新建一个service文件夹,新建一个接口和实现类代码如下:
package com.yyliu1.service.interfacer;
/*
@auther 刘阳洋
@date 2030/4/21 17:53
*/
public interface UserService {
String testService();
}
package com.yyliu1.service.impl;/*
@auther 刘阳洋
@date 2030/4/21 17:54
*/
import com.unionpay.ysf.service.interfacer.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public String testService() {
return "hello sprintboot2";
}
}
10、添加web启动器,因为device-web引入了device-service所以直接在device-service里面添加就行,打开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">
<parent>
<artifactId>device-parent</artifactId>
<groupId>com.unionpay.ysf</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-service</artifactId>
<dependencies>
<!--web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
11、测试并且启动第一个hello sprintboot2接口,点击device-web的SpringBootWebApplication 类,右键—Run
12、如下图所示第一个程序就这么简单的跑起来了。
13、前两节最重要的是如何建立多模块和模块间如何引用,看到这里想必你已经对springboot2有一个直观的感受了。接下来跟我一起进入springboot2的世界吧!!
第三节、公司内网情况下构建springboot2项目
1、由于公司没有外网,一般公司都有自己的的maven仓库,首先要有一定的基础,你需要自己的将公司的maven库配置到IDEA里面,网上有很多教程这里不再赘述。
2、打开IEDA—FILE—NEW—Project—Maven—NEXT—GroupId和ArtifactId按照自己的风格填写—NEXT—FINISH(注意这里的项目名也可以按照自己的风格取,多创建几次就熟悉了)—NEW WINDOW
3、到此一个maven工程就创建完毕,打开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>com.unionpay.yyliu1</groupId>
<artifactId>maven-project</artifactId>
<version>1.0-SNAPSHOT</version>
<!--添加父类工程坐标-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<!--指定JDK版本-->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--引入web启动器,这一步很重要自动帮我们加载spring相关的依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入单元测试junit-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
4、创建启动类,在src–main–java下点击右键java—NEW—package—创建一个com.unionpay.yyliu1这个包,然后在这个包上右键—NEW—java 新建一个启动类SpringBoot2Application
package com.unionpay.yyliu1;
/*
@auther 刘阳洋
@date 2020/4/22 10:13
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBoot2Application {
public static void main(String []args){
SpringApplication.run(SpringBoot2Application.class,args);
System.out.println("springboot2启动成功");
}
}
5、调试你创建的springboot2是否创建成功,首先新建一个controller包,在这个包下面新建一个类代码如下:
package com.unionpay.yyliu1.controller;/*
@auther 刘阳洋
@date 2020/4/22 10:18
*/
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/test")
public String hello(){
return "hello springboot2";
}
}
6、点击启动类SpringBoot2Application右键Run启动 如图
7、打开浏览器输入http://localhost:8080/hello/test可以看到如下图所示的字符串,证明我们的接口调试成功,至此我们的内网情况下的springboot2项目创建完成
第四节、配置文件读取
1、properties配置文件读取
1、经过以上的操作新建项目就不用赘述了,直接跳过。新建一个springboot2项目,注意不要用maven建,要用springboot2初始化器: Spring Initializr建项目,新建好以后。
2、在resource资源目录下新建一个people.properties
people.username=liuyangyang
people.salary=2000
people.age=20
people.sex=male
3、在java目录下新建一个entity的包,然后在这个包下面建一个People.java类
package com.springboot.configuration.entity;/*
@auther 刘阳洋
@date 2020/4/22 12:46
*/
import org.springframework.context.annotation.PropertySource;
public class People {
private String username;
private double salary ;
private int age;
private String sex;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "People{" +
"username='" + username + '\'' +
", salary=" + salary +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
3、新建一个config包在下面建一个PeopleConfig.java类
package com.springboot.configuration.config;/*
@auther 刘阳洋
@date 2020/4/21 18:24
*/
import com.springboot.configuration.entity.People;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value={"classpath:people.properties"})
public class PeopleConfig {
@Value("${people.username}")
private String username;
@Value("${people.salary}")
private double salary;
@Value("${people.age}")
private int age;
@Value("${people.sex}")
private String sex;
@Bean
public People getPeople(){
People people=new People();
people.setUsername(username);
people.setSalary(salary);
people.setAge(age);
people.setSex(sex);
return people;
}
}
4、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>configuration</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
5、在test目录下 有一个自动给我们建好的类,点进去进行修改如下
package com.springboot.configuration;
import com.springboot.configuration.entity.People;
import com.springboot.configuration.utils.JwtTokenUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationApplicationTests {
@Autowired
private People people;
@Test
public void TestPeople(){
System.out.println(people.toString());
}
}
6、搞定以后点击TestPeople()这个方法右键运行测试结果如下:
7、如果在配置文件中输入中文可能会乱码,这个时候就要用到yaml格式,因为yaml格式的配置文件天生支持UTF-8,而properties配置文件支持ISO-8859-1/ASCII所以中文会乱码。
2、yaml配置文件读取
1、新建application-person.yam文件内容如下
person:
username: zhangsan
salary: 20000
age: 28
sex: male
pets: cat,dogs
list:
- lisi
- wangwu
friend:
name: laoliu
age: 30
children:
- name: wangwu
age: 10
- name: nima
age: 10
- name: sasa
age: 100
- name: dasdas
age: 300
employee:
name: lisi
age: 30
2、pom.xml文件不变,在application.yaml文件中添加如下
spring:
profiles:
active: person
3、新建一个Person.java类
package com.springboot.configuration.entity;
/*
@auther 刘阳洋
@date 2020/4/21 18:21
*/
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
private String username;
private double salary ;
private int age;
private String sex;
private String[] pets;
private List<String> list;
private Map<String,String> friend;
private List<Map<String,String>> children;
private Employee employee;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String[] getPets() {
return pets;
}
public void setPets(String[] pets) {
this.pets = pets;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public Map<String, String> getFriend() {
return friend;
}
public void setFriend(Map<String, String> friend) {
this.friend = friend;
}
public List<Map<String, String>> getChildren() {
return children;
}
public void setChildren(List<Map<String, String>> children) {
this.children = children;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", salary=" + salary +
", age=" + age +
", sex='" + sex + '\'' +
", pets=" + Arrays.toString(pets) +
", list=" + list +
", friend=" + friend +
", children=" + children +
", employee=" + employee +
'}';
}
}
4、新建一个Employee.java类
package com.springboot.configuration.entity;/*
@auther 刘阳洋
@date 2020/4/21 18:47
*/
public class Employee {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
5、注入Person,新建一个测试方法 TestPerson(),右键TestPerson然后Run运行
package com.springboot.configuration;
import com.springboot.configuration.entity.Person;
import com.springboot.configuration.utils.JwtTokenUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationApplicationTests {
@Autowired
private Person person;
@Test
public void TestPerson(){
System.out.println(person.toString());
}
}
6、如下图所示
第五节、配置文件多环境读取
1、如图所示新建三个不同环境的yaml配置文件
2、application.yaml里代码如下:
spring:
profiles:
active: dev
3、application-dev.yaml代码如下:
server:
port: 8081
branch: dev
4、application-prod.yaml代码如下:
server:
port: 8082
branch: product
5、application-test.yaml代码如下:
server:
port: 8083
branch: test
6、在controller包下面新建一个TestController.java类
package com.example.demoprofile.controller;/*
@auther 刘阳洋
@date 2020/4/22 10:48
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class TestController {
@Value("${branch}")
private String branch;
@GetMapping("/test")
public String test(){
return branch;
}
}
7、点击IDEA右边的maven project,先双击击clean,然后再双击install,等待打包结束。找到你IDEA项目路径E:\device系统\demo-profile\target 下面就可以看到你打好的jar包
8、然后在上方输入cmd
9、然后在命令提示行里面输入
java -jar demo-profile-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
目的是为了指定配置文件启动
10、浏览器输入http://localhost:8083/test/hello
结果如下:
第六节、静态工具类读取配置文件
1、在entity包下面新建TokenSettings.java类
package com.springboot.configuration.entity;
/*
@auther 刘阳洋
@date 2020/4/21 20:19
*/
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "jwt")
public class TokenSettings {
private String secretKey;
private String issuer;
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
}
2、新建utils包,在此包下新建JwtTokenUtils.java
package com.springboot.configuration.utils;/*
@auther 刘阳洋
@date 2020/4/21 20:22
*/
import com.springboot.configuration.entity.TokenSettings;
public class JwtTokenUtils {
private static String secretKey;
private static String issuer;
//初始化
public static void setTokenSettings(TokenSettings tokenSettings){
secretKey=tokenSettings.getSecretKey();
issuer=tokenSettings.getIssuer();
}
public static String getToken(){
return secretKey+issuer;
}
}
3、再新建StaticInitializerUtil.java
package com.springboot.configuration.utils;
/*
@auther 刘阳洋
@date 2020/4/21 20:26
*/
import com.springboot.configuration.entity.TokenSettings;
import org.springframework.stereotype.Component;
@Component
public class StaticInitializerUtil {
public StaticInitializerUtil(TokenSettings tokenSettings){
JwtTokenUtils.setTokenSettings(tokenSettings);
}
}
4、application.yaml里面改为如下:
jwt:
secretKey: xxxxxfdsfxxx
issuer: vingxue.com
5、测试类修改为如下
package com.springboot.configuration;
import com.springboot.configuration.utils.JwtTokenUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationApplicationTests {
@Test
public void TestToken(){
System.out.println(JwtTokenUtils.getToken());
}
}
6、TestToken上面点击右键然后Run 结果如下图
第七节、Springboot2过滤器
1、新建springboot项目 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>filter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>filter</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.yaml
#凡是请求带有open的都放行
openUrl: /**/open/**
3、新建一个Filter.java类
package com.example.filter.filter;/*
@auther 刘阳洋
@date 2020/4/22 17:00
*/
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class MyFilter implements Filter {
@Value("${openUrl}")
private String openUrl;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("MyFilter被初始化了");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
String uri=request.getRequestURI();
String method=request.getMethod();
System.out.println("请求的接口="+uri+"请求方式="+method);
//判断是否是开放性API
AntPathMatcher antPathMatcher= new AntPathMatcher();
if(antPathMatcher.match(openUrl,uri)){
filterChain.doFilter(servletRequest,servletResponse);
}else{
String token =request.getHeader("token");
if(StringUtils.isBlank(token)){
servletRequest.getRequestDispatcher("/api/open/unLogin").forward(servletRequest,servletResponse);
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
}
@Override
public void destroy() {
System.out.println("MyFilter被销毁了");
}
}
4、新建一个FilterCofigure.java类
package com.example.filter.configure;
/*
@auther 刘阳洋
@date 2020/4/23 11:11
*/
import com.example.filter.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterCofigure {
@Bean
public MyFilter myFilter(){
return new MyFilter();
}
@Bean
public FilterRegistrationBean getFilterRegistrationBean(MyFilter myFilter){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(myFilter);
filterRegistrationBean.setOrder(1);
filterRegistrationBean.addUrlPatterns("/api/*");
filterRegistrationBean.setName("myFilter");
return filterRegistrationBean;
}
}
5、新建TestController.java类
package com.example.filter.controller;/*
@auther 刘阳洋
@date 2020/4/22 17:13
*/
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class TestController {
@GetMapping("/user/filter")
public String myfilter()
{
return "你好我被filter监控了";
}
//写一个开放性的接口
@GetMapping("/home/open/info")
public String getHome(){
return "欢迎访问首页";
}
@GetMapping("open/unLogin")
public String getUnLogin(){
return "登录失效,请重新登录 ";
}
}
6、测试
http://localhost:8080/api/home/open/info http://localhost:8080/api/user/filter 先打开浏览器测试,多观察就知道原理所在
再打开postman测试
输入token就可以进行测试如图所示
第八节、Springboot2拦截器
1、pom.xml和application.yaml与上面过滤器的一样
2、新建MyIntercepter.java类
package com.example.interceptor.intercepters;/*
@auther 刘阳洋
@date 2020/4/23 16:16
*/
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截方法请求之前调用");
String requestUri=request.getRequestURI();
System.out.println(requestUri+"接口被拦截了");
//判断用户是否携带凭证
String token=request.getHeader("token");
if(StringUtils.isEmpty(token)){
request.getRequestDispatcher("/api/open/unLogin").forward(request,response);
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截方法请求之后调用");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("整个流程结束调用");
}
}
3、新建WebApplicationConfig.java类
package com.example.interceptor.config;
/*
@auther 刘阳洋
@date 2020/4/23 16:20
*/
import com.example.interceptor.intercepters.MyIntercepter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebApplicationConfig implements WebMvcConfigurer {
@Value("${openUrl}")
private String openUrl;
@Bean
public MyIntercepter myIntercepter(){
return new MyIntercepter();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置策略
registry.addInterceptor(myIntercepter()).addPathPatterns("/api/**").
excludePathPatterns(openUrl);
}
}
4、新建
package com.example.interceptor.controller;/*
@auther 刘阳洋
@date 2020/4/23 16:29
*/
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ControllerTest {
@GetMapping("/home/open/info")
public String interceptor(){
return "欢迎来到首页";
}
@GetMapping("/user/interceptor")
public String user(){
return "我被拦截了并通过了拦截器";
}
@GetMapping("open/unLogin")
public String getUnLogin()
{
return "登录失效,请重新登录 ";
}
}
5、 进行测试
http://localhost:8080/api/home/open/info http://localhost:8080/api/user/interceptor
先打开浏览器测试,多观察就知道原理所在
再打开postman测试
输入token就可以进行测试如图所示
第九节、SpringMVC静态资源路径
1、classpath:/META-INF/resources/
2、classpath:/resources/
3、classpath:/static/
4、classpath:/public
只要静态资源放在这些目录的任何一个地方springmvc都会帮我们处理,我们习惯会把静态资源放在static目录下。
5、找一张图片放到static目录下timg.jpg
6、启动应用然后进行访问
http://localhost:8080/timg.jpg
第十节、SpringBoot整合Jsp
1、 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>interceptor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>interceptor</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<!--内置容器支持jsp-->
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<!--添加jsp标签-->
<groupId>javax.servlet</groupId>
<artifactId>jstl</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-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、创建index.jsp页面,src–右键main,新建一个文件夹webapp
然后ctrl+alt+shift+s
如上图,选择Moudle—Web—点击+号–web.xml
选择路径是你新建的webapp那个路径
E:\device系统\interceptor\src\main\webapp
点击OK,然后在下面也同样点击+号指定路径
E:\device系统\interceptor\src\main\webapp
Apply—OK完成3、在webapp下新建目录结构如下图,验证是否创建成功要看到webapp那个文件夹图标是否有个蓝色的点即验证成功
4、新建jsp页面并且输入内容 index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/23
Time: 19:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>你好</title>
</head>
<body>
springboot整合jsp成功
</body>
</html>
5、新建测试接口JspController.java
package com.example.interceptor.controller;/*
@auther 刘阳洋
@date 2020/4/23 19:46
*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class JspController {
@GetMapping("/index")
public String index(){
return "index";
}
}
6、测试 浏览器输入 http://localhost:8088/index
第十一节、springboot整合thymeleaf
1、新建springboot2项目,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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>thymeleaf</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.yaml
server:
port: 8088
#thymeleaf默认html和默认文件夹 所以不用指定前缀和后缀
spring:
thymeleaf:
encoding: UTF-8
servlet:
content-type: text/html
3、在resources资源目录templates下新建一个index.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎</h1>
<p th:text="${username}"></p>
</body>
</html>
4、新建ThymeleafController.java
package com.example.thymeleaf.controller;
/*
@auther 刘阳洋
@date 2020/4/23 20:44
*/
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String thyme(Model model){
model.addAttribute("username","刘阳洋");
return "index";
}
}
5、测试
http://localhost:8088/thymeleaf
第十二节、springboot整合freemarker
1、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>freemarker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>freemarker</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</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-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.yaml
server:
port: 8088
#freemarker默认html和默认文件夹 所以不用指定前缀和后缀
spring:
banner:
charset: UTF-8
freemarker:
content-type: text/html
suffix: .html
3、在resources资源目录templates下新建一个index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>你好</title>
</head>
<body>
<h1>你好</h1>
<h1>${username}</h1>
</body>
</html>
4、新建FreemarkerController.java
package com.example.freemarker.controller;/*
@auther 刘阳洋
@date 2020/4/23 21:10
*/
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FreemarkerController {
@GetMapping("/freemarker")
public String free(Model model){
model.addAttribute("username","刘阳洋freemarker");
return "index";
}
}
5、测试
http://localhost:8088/freemarker