Spring Boot
/**
* 只有在容器中的組件,才能擁有springboot的功能
*/
//@Component//將組件加到容器中
@ConfigurationProperties(prefix = "mycar")//prefix指的組態檔里的前綴相系結
public class Car {
private String brand;
private Integer price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
/**
* 1、配置類里面使用@Bean標注在方法上給容器注冊組件,默認也是單實體的
* 2、配置類本身也是組件
* 3、proxyBeanMethods :代理bean的方法
* Full(proxyBeanMethods = true) 為true時發現呼叫一次之后就繼續使用該物件
* Lite(proxyBeanMethods = false) 為false時每次呼叫就會產生一個新物件
* 組件依賴
* 4、@Import({User.class}):給容器中自動創建出寫入型別的組件,默認組件名字就是全類名
*/
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = true)//告訴springboot這是一個配置類 等同于 以前的組態檔 proxyBeanMethods默認為true
//@ConditionalOnMissingBean(name = "")//容器中沒有括號內組件時,執行下面代碼
//@ImportResource("classpath:xxx.xml")//當你有xml型別的組件組態檔時,可以在用這個注解匯入,會自動將這個xml檔案的組件注入到容器當中
@EnableConfigurationProperties(Car.class)
//1、開啟Car的配置系結功能2、把Car這個組件自動注入到容器中(或者不寫這個,在Car類中增加一個@Component注解)
public class MyConfig {
/**
* 外部無論對這個配置類中的組件注冊方法呼叫多少次,獲取的都是之前注冊到容器中的單實體物件
* @return
*/
@Bean //給容器中添加組件:以方法名作為組件id,回傳型別就是組件型別,回傳的值就是組件在容器中保存的實體
public User user01(){
User zhangsan = new User("張三",18);
//User組件依賴了Pet組件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@ConditionalOnBean(name = "user01")//當容器中有user01組件時,下面代碼才生效,可以放在類上面,也可以放在方法上面
@Bean("TomCat")//可以給容器組件自定義名字
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
//@ResponseBody
//@Controller
@RestController//就是ResponseBody和Controller注解的合體
public class HelloController {
@ResponseBody//表示該類回傳的資料直接回傳給瀏覽器
@RequestMapping("/hello")
public String handle01(){
return "Hello,SpringBoot 2!";
}
@Autowired//自動注入
Car car;
@RequestMapping("/car")
public Car car(){
return car;
}
}
Starter
dev Tools
? 熱更新:Ctrl + F9 代碼修改后,快捷鍵直接重啟系統,但其實和restart沒多大區別
依賴注入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Spring Initializer
? 新建專案的時候選擇,直接選擇專案所需要的檔案,自動引入依賴
核心功能
組態檔
類前面要加上對應的系結
@ConfigurationProperties( prefix = "xxx" )//xxx對應yml檔案里的key值
public class xxxx{
}
-
? 第一種:application. Properties 組態檔
-
? 第二種:yaml 檔案 適合用來做以資料為中心的組態檔
基本語法:
key:value ;(冒號后有一個空格)
使用縮進表示層級關系
縮進不允許使用tap,只允許使用空格(idea中可以用tap)
縮進的空格數不重要,只要相同層級的元素左對齊即可
“#”表示注釋
字串無需加引號,如果要加 ,' ' 和 " " 表示字串內容,會被轉義/不轉義
k: v #鍵值對寫法:map、hash、set、object 行類寫法:k: {k1:v1,k2:v2,k3:v3} 或者: k: k1: v1 k2: v2 k3: v3 #陣列寫法:array、list、queue 行類寫法:k: [v1,v2,v3] #寫法 k: - v1 - v2 - v3在寫組態檔時,引入下面依賴,可以在配置時自動提示
---
Web開發
靜態資源訪問
1、靜態資源目錄
只要靜態資源在 static 或 resources 或 public 或 META-INF/resources 檔案下
在瀏覽器直接請求靜態資源檔案名就可以得到:localhost:8080/(靜態資源檔案名)
原理:先通過請求找到controller里面有沒有相應的request mapping如果沒有,再去靜態資源檔案夾區找相應的靜態資源,如果靜態資源找不到,就會404
2、靜態資源訪問前綴
默認無前綴
spring:
mvc:
static-path-pattern: /res/**
#設定靜態資源訪問前綴,訪問靜態資源時必須加上設定的前綴
resources:
static-locations: [classpath:/haha/]
#[]是陣列寫法,可以配置多個訪問檔案夾
#設定靜態資源訪問檔案夾,設定完成后,系統只在設定的檔案加里面訪問靜態資源
歡迎頁支持(index)
靜態資源路徑下 index.html
? 可以配置靜態資源路徑
? 但是不可以配置靜態資源的訪問前綴,否則就會導致index.html不能被默認訪問
controller能處理/index
自定義 Favicon (網頁圖示)
將命名為 favicon.ico 的圖片放在靜態資源目錄下面,springBoot會自動將圖示設定為網頁圖示
請求引數注解使用
@RequestParam()注解:獲取前端引數包括表單引數
@RequestMapping("/user")
public String hello(@RequestParam("username") String name){//獲取路徑中問號后面傳入的值
}
//也可以通過直接傳入session的方式
public String hello(HttpSession session){
}
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar( @RequestParam("age")Integer age,
@RequestParam("inters")List<String> inters,
@RequestParam Map<String,String> params){//直接獲取所有引數并用Map來接
Map<String,Object> map = new HashMap<>();
map.put("age",age);
map.put("inters",inters);
map.put("params",params);
return map;
}
@PathVariable()注解:獲取路徑中的變數
@RequestHeader()注解:獲取請求頭,不帶引數獲取全部,帶引數獲取單個
<a href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/car/3/owner/lisi">car/3/owner/lisi</a>
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@PathVariable("id") Integer id,
@PathVariable("username") String name,//這個@PathVariable和@GetMapping大括號里的一一對應
@RequestHeader("User-Agent") String userAgent,//獲取請求頭
@RequestHeader() Map<String,String> header){//獲取請求頭
Map<String,Object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
map.put("userAgent",userAgent);
map.put("header",header);
return map;
}
}
@CookieValue()獲取cookie的值
public String test(@CookieValue("")String name){
}
@RequestBody():獲取請求體
@PostMapping("/save")
public Map PostMeth(@RequestBody String content){
Map<String,Object> map = new HashMap<>();
map.put("content",content);
return map;
}
{"content":"userName=2222&email=2222"}
@RequestAttribute():獲取request中的值
? 只可以獲取request設定的值,不能獲取前端表單的值
@Controller
public class RequestController {
@GetMapping("/goto")
public String gotopage(HttpServletRequest request){
request.setAttribute("msg","成功了");
return "forward:/success";
}
@ResponseBody
@GetMapping("/success")
public String success(@RequestAttribute("msg") String msg){
return msg;
}
}
@MatrixVariable()矩陣變數
/car/Path?xxx=xxx&xxx=xxx @RequestParam
/car/Path;xxx=xxx;xxx=xxx,xxx,xxx矩陣變數
頁面開發,cookie禁用了,session里的應用怎么使用
? session.set(a,b) ---> jsessionid --->cookie ---> 每次發請求攜帶
? URL重寫:/abc;jsessionid=xxxx 把cookie的值使用矩陣變數的方式進行傳遞
<a href="https://www.cnblogs.com/cars/sell;low=34;brand=byd,audi,yd">@MatrixVariable(矩陣變數)</a>
<a href="https://www.cnblogs.com/cars/sell;low=34;brand=byd;brand=audi;brand=yd">@MatrixVariable(矩陣變數)</a>
<a href="https://www.cnblogs.com/boss/1;age=20/2;age=10">@MatrixVariable(矩陣變數)/boss/bossid/empid</a>
//springboot默認禁用了矩陣變數功能
//手動配置:原理:對于路徑處理,都是用UrlPathHelper進行決議,removeSemicolonContent(翻譯:移除翻譯內容)支持矩陣變數
@GetMapping("/cars/{Path}")//這個地方要寫Path而不是具體的路徑
public Map carsSell(@MatrixVariable("low") Integer low,
@MatrixVariable("brand") List<String> brand){
Map<String,Object> map = new HashMap<>();
map.put("low",low);
map.put("brand",brand);
return map;
}
手動配置矩陣變數:增加配置類
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
public void configurePathMatch(PathMatchConfigurer configurer){
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);//設定為不移除分號后面的內容
configurer.setUrlPathHelper(urlPathHelper);
}
};
}
視圖決議與模板引擎
? springboot默認不支持 jsp,需要進入第三方模板引擎技術
Thymeleaf
不建議使用在高并發的環境下,建議前后端分離
pom.xml 整合Thymeleaf 需要的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
使用Thymeleaf需要在HTML頁面中加上這一句
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}">哈哈</h1><!--msg沒有內容的話還是顯示哈哈有內容就顯示內容的值-->
<h2><a th:href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/${link}">去百度$</a></h2><!--地址直接指向link的值-->
<h2><a th:href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/@{link}">去百度@</a></h2><!--地址直接指向的絕對路徑的地址-->
</body>
</html>
@GetMapping("/hhh")
public String hhh(Model model){
//model中的資料會被自動放在請求域中 相當于request.setAttribute(“xx”,xx)
model.addAttribute("msg","你好 hhh");
model.addAttribute("link","http://www.baidu.com");
return "success";
}
在行內獲取后臺引數的寫法:
[[${session.loginUser.name}]]
獲取公共頁面(相當于以前的 jsp:incude)
<!-- 公共頁面common.html -->
<head th:fragment="commonheader" id="commonheader"> <!-- th:fragment="commonheader" 就是該標簽的名字 -->
<!--common-->
<link href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/css/style.css" th:href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/@{/css/style.css}" rel="stylesheet">
<link href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/css/style-responsive.css" th:href="https://www.cnblogs.com/gscicoding/archive/2021/04/11/@{/css/style-responsive.css}" rel="stylesheet">
</head>
<!-- 參考公共頁面時 -->
<link th:replace="~{common :: commonheader}"> <!-- common就是參考頁面的名字,commonheader就是參考標簽的名字 -->
<link th:replace="~{common :: #commonheader}"> <!-- 如果是參考id就在id名前加上#號 -->
<!--
有replace、include、insert三個th標簽
replace:替換現有標簽,直接參考參考的標簽
include(不建議使用):僅僅將參考標簽中的內容增加進來
insert:保留現有標簽,在其中插入參考的標簽
-->
資料遍歷:使用 th:each 獲取后臺的資料
<tr th:each="user:${users}">
<td>Trident</td>
<td th:text="${user.userName}">Internet Explorer 4.0</td>
<td th:text="${user.passWord}">[[${user.password}]]</td>
</tr>
@GetMapping("/dynamic_table")
public String dynimic_table(Model model){
//表格內容遍歷
List<User> users = Arrays.asList(new User("zhangsan","123456"),
new User("lisi","123444"),
new User("haha","aaaaa"));
model.addAttribute("users",users);
return "table/dynamic_table";
}
攔截器
HandlerInterceptor
/**
* 登陸檢查(攔截器)
* 1、配置好攔截器要攔截哪些請求
* 2、把這些配置放在容器中
*/
public class LoginInterceptor implements HandlerInterceptor {
/**
* 目標方法執行之前
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登錄檢查邏輯
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if (loginUser != null){
//return true就是放行
return true;
}
//攔截住,未登錄,跳轉到登錄頁面
session.setAttribute("msg","請先登錄");
response.sendRedirect("/");
//false就是攔截
return false;
}
/**
* 目標方法執行完成以后
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
*頁面渲染以后
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
/**
* 開發web專案配置的時候都要實作WebMvcConfigurer介面
* 1、撰寫一個攔截器 實作 HanderInterceptor 介面
* 2、攔截器注冊到容器中(實作WebMvcConfigurer的addInterceptors)
* 3、指定攔截規則(如果攔截所有靜態資源也會被攔截)
*/
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())//添加自己配置的攔截器
.addPathPatterns("/**")//攔截哪些請求(靜態資源也會被攔截)
.excludePathPatterns("/","/login","/css/**","/font/**","/images/**","/js/**");//放行哪些請求
}
}
檔案上傳
? 檔案上傳表單格式:
<form role="form" th:action="@{upload}" method="post" enctype="multipart/form-data">
后臺將檔案存盤進服務器中
/**
* 檔案上傳
* MultipartFile 自動封裝上傳過來的檔案
* @param email
* @param username
* @param headerImg
* @param photos
* @return
*/
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("上傳的資訊:email={},username={},headerImg={},photos={}", email,username,headerImg.getSize(),photos.length);
if(!headerImg.isEmpty()){
//保存到檔案服務器,OSS服務器
String originalFilename = headerImg.getOriginalFilename();//獲取檔案原始名
headerImg.transferTo(new File("D:\\Test\\"+originalFilename));//將檔案保存在相應的
}
//處理多個檔案
if (photos.length > 0){
for (MultipartFile photo : photos){
if (!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();//獲取檔案原始名
photo.transferTo(new File("D:\\Test\\" + originalFilename));
}
}
}
return "main";
}
#設定單個檔案上傳最大大小
spring.servlet.multipart.max-file-size=10MB
#設定所有檔案上傳最大大小
spring.servlet.multipart.max-request-size=100MB
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/274986.html
標籤:其他
