1分鐘學會SpringBoot2知識點,讓你35歲不再失業(一)
目錄
第一節、快速構建項目
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