SpringBoot基礎使用

一、SpringBoot 介紹
 
  官網://start.spring.io/;阿里雲伺服器地址://start.aliyun.com/
spring boot是一套快速使用spring產品的便捷工具
特點:絕對沒有程式碼生成並且對XML也沒有配置要求、提供生產就緒型功能,如指標,健康檢查和外部配置、儘可能自動配置Spring和第三方庫、簡化構建配置、嵌入的Tomcat,無需部署WAR文件、創建獨立的Spring應用程式SpringApplication.run(…)默認會載入classpath下的application.yml或application.properties配置文件
二、SpringBoot版的Spring MVC
 
  1、新建Spring Starter Project、選war包,功能選擇web、devtools兩個功能模組
 
  2、工程介紹
 
 
目錄名
目錄作用
src/main/resources/static
可被外部訪問,等同於webapp目錄、用來存放靜態資源;所有訪問的資源 默認從static路徑訪問、html也默認訪問static、除非添加對應模板的jar包、才會默認訪問templates
src/main/resources/templates
文件夾是受保護的、只允許被伺服器訪問,等同於web-inf目錄<br>springboot推薦使用Thymeleaf 、Freemarker等模板、並不支援JSP模板<br>導入jar包後、會變成靜態模板的默認路徑
  3、創建一個普通類、使用SpringMVC的註解@Controller、@RestController、@RequestMapping等註解
 
@RestController
@RequestMapping("/student")
public class StudentController {
    @RequestMapping("/show1")
    public Object show1() {
        return "show11111111";
    }
}
4、啟動Springboot001Application類、SpringBoot項目默認集成了Tomcat的jar包,故無需依賴tomcat可直接運行
 
@SpringBootApplication(scanBasePackages = "包名")
public class Springboot001Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot001Application.class, args);
    }
}
三、自定義配置文件
 
我們都把配置文件寫到application.yml中。有時我們不願意把配置都寫到application配置文件中,這時需要我們自定義配置文件,比如person.properties
 
1、student.properties
 
info.name=admin
info.pwd=123456
info.cinfo.name=一年一班
 
2、Student實體類配置
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

//載入屬性文件
@PropertySource("classpath:/properties/student.properties")
//屬性文件的配置
@ConfigurationProperties(prefix = "info")
@Component
public class Student {
    private int id;
    private String name;
    private String pwd;
    private String img;
    private int classid;
    private Classes cinfo;
    //get、set和構造函數省略
}
3、StudentController的配置
@RestController
@RequestMapping(/student)
public class StudentController {
    //如果已經在其他地方使用@PropertySource則此處可直接使用
    //否則需要在這個controller上面添加@PropertySource註解
    @Value(${info.name})
    private String name;
    @Value(${info.pwd})
    private String pwd;

    @Autowired
    Student info;
   
    @RequestMapping(/show1)
    public Object show1() {
        return info;
    }
   
    @RequestMapping(/show2)
    public Object show2() {
        return 2222+this.name+,+this.pwd;
    }
}
 
四、過濾器的使用
1、使用過濾器、務必在啟動類添加 @ServletComponentScan(basePackages = “包名“)
 
mport java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class CoreFiler implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request2 = (HttpServletRequest) request;
        HttpServletResponse response2 = (HttpServletResponse) response;

        // 添加參數,允許訪問我的域名跨域--->request2.getHeader("Origin"):誰訪問的我
        response2.setHeader("Access-Control-Allow-Origin", request2.getHeader("Origin"));
        // 允許客戶端攜帶驗證資訊
        response2.setHeader("Access-Control-Allow-Credentials", "true");
        // 這個allow-headers要配為*,這樣才能允許所有的請求頭 ---
        response2.setHeader("Access-Control-Allow-Headers", "*");
        // 允許的請求方式
        response2.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        // 複雜請求多少秒內、不需要預請求(複雜請求:在請求的head裡面添加參數)
        // response2.setHeader("Access-Control-Max-Age", "100000");
        System.out.println("CoreFilter執行!!!!!");
        chain.doFilter(request2, response2);
    }
}
2、使用@CrossOrigin註解、@CrossOrigin既可使用在Controller
@RestController
@RequestMapping("/student")
//整個Controller的方法皆可跨域
@CrossOrigin
public class StudentController {
    
    //單個方法支援跨域
    @CrossOrigin
    @RequestMapping("/show1")
    public Object show1() {
        return "show1";
    }
}
3、使用SpringBoot的全局配置
 
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(/**)
        .allowedOriginPatterns(*)
        .allowCredentials(true)
        .allowedMethods(GET, POST, DELETE, PUT)
        .maxAge(3600 * 24);
    }
}
 
五、Linux後台啟動SpringBoot項目命令
 
shell命令:    
nohup java -jar springbootssm-0.0.1-SNAPSHOT.jar > /log/springbootssm.out 2>&1 &
六、靜態資源文件訪問配置
 
# 映射到地址欄的路徑設置 比如//localhost:8080/aaa/1.jpg
spring.mvc.static-path-pattern=/aaa/**
# 實際的圖片映射路徑  實際訪問的是 //localhost:8080/image/1.jpg  
# 可以是本項目地址、亦可以是本地電腦的絕對路徑地址、亦亦可是網路路徑地址
spring.web.resources.static-locations=file:d://img/,classpath:image/,//47.100.96.196:8080/img/