Table of contents
- lead out
- Basic knowledge: three-tier architecture and MVC
- springWeb project IDEA construction
- SpringMvc browser request preliminary
- The way the browser requests Request to pass parameters
-
- 1. Basic data types and String
- 2. Send name, receive is username, @RequestParam(value = "name")
- 2. [Application] Paging can use @RequestParam(value = "pageNum", defaultValue = "1")
- 3.Rest style query xxx/search/mobile phone/white----xxx/search?item=mobile phone&color=white
- 4. The backend uses object reception + array/collection
- 5. Date processing, the default format is 2021/05/28, [to be continued]
- 6. How to get the request header, the value in the cookie, and the original request and response, etc.
- The server responds to Response---the backend sends content to the frontend
- SpringMvc handles uploading files
-
- 1. Upload the file and save it to the local MultipartFile
- 2. The problem that the uploaded file with the same name is overwritten --- rename with uuid
- 3. Display local computer pictures --- static resource mapping -- protocol file:
- 4. Put the path of the uploaded file in the spring configuration file and get @Value("${imgLocation}")
- Summarize
lead out
What is mvc, what is springMvc, how to build a springWeb project,
how to send requests and responses under springMvc, and how to respond?
SpringMvc processing files related: upload files, rename uuid, static resource mapping, yaml configuration path, preliminary spring configuration file;
Basic knowledge: three-tier architecture and MVC
1. Three-tier architecture
- Presentation (view) layer: WEB layer, used for data interaction with clients. servlet-controller
- Business layer: service that handles company-specific business logic
- Persistence layer: dao-mapper used to operate the database
2. MVC model
-
The full name of MVC is Model View Controller Model View Controller, and each part performs its own duties.
-
Model: data model, JavaBean class, used for data encapsulation.
-
View: Refers to JSP and HTML used to display data to users Android-http, Apple, applets
-
Controller: used to receive user requests, the controller of the entire process. Used for data verification, etc.
springWeb project IDEA construction
1. Create a new normal maven project
2. Import package, pom.xml file
(1) Inherit a parent
<!-- 继承一个父-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
(2) Package of web project + front-end template engine
<!-- 做web项目的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 前端模板引擎,类似于jsp-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(3) Complete pom.xml file
<?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.tianju</groupId>
<artifactId>springMvc620</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 继承一个父-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 做web项目的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 前端模板引擎,类似于jsp-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 其他需要的包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.22</version>
</dependency>
</dependencies>
</project>
3. Write the main startup class Main.java file @SpringBootApplication
Main points:
- It is the configuration class of spingMvc: @SpringBootApplication;
- Start: SpringApplication.run(Main.class);
- The problem of directory hierarchy, and other directories of the same level;
Main.java file
package com.tianju;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
/**
* springMvc的主启动类
* 1.本质是配置类;@SpringBootApplication :@Configuration是它的爷爷辈
* 2.启动容器,SpringApplication.run(Main.class);
*/
@SpringBootApplication
public class Main {
public static void main(String[] args) {
// 集成了的new对象,放容器,启动执行
ApplicationContext ac = SpringApplication.run(Main.class);
}
}
4. Write the application.yml file spring configuration file
Main points:
- The file name is application.yml
- If the color is yellow, there must be a space
server:
port: 80
5. Start, run main.java to start
SpringMvc browser request preliminary
1. Getting to know springMvc @RequestMapping("/demo")
Main points:
- 1. The controller should be in the container: @Controller
- 2. Used to process browser requests: @RequestMapping(“/demo”)
- @RequestMapping("/demo") can be on the class or on the method: first-level and second-level directories;
ResponseControllerDemo.java file
package com.tianju.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
@RequestMapping({
"/hello","/hello2"}) // 二级目录
@ResponseBody
public String hello(){
return "Hello SpringMvc";
}
}
2. Derived from @RequestMapping
@PostMapping,@GetMapping,@DeleteMapping,@PutMapping
@RequestMapping
@PostMapping(“/hello”)
@GetMapping
@DeleteMapping
@PutMapping
405 exception: the server can only process post, and the browser requests the get method
The way the browser requests Request to pass parameters
1. Basic data types and String
Main points:
- If the string is not passed, the default is an empty string;
- Integer is not passed, the default is null;
http://localhost/demo/hello?username=&age=
package com.tianju.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
@RequestMapping("/hello") // 二级目录
@ResponseBody
public String hello(String username,Integer age){
System.out.println(username);
System.out.println(age);
return "Hello SpringMvc";
}
}
2. Send name, receive is username, @RequestParam(value = "name")
Main points:
-
By default, the value must be passed, and if it is not passed, a 400 exception will be reported;
-
If you don't want to pass it, add required=false;
-
You can also give a default value, defaultValue="admin"; [Application: When paging, the default is the first page, and the default is 10 data per page]
http://localhost/demo/hello?name=hell
@RequestMapping("/hello") // 二级目录
@ResponseBody
public String hello(@RequestParam(value = "name") String username){
System.out.println(username);
return "Hello SpringMvc";
}
400 exception, added @RequestParam(value = "name") must pass value
400 exception, the backend type is Integer, the frontend is string, and the conversion fails
2. [Application] You can use @RequestParam(value = “pageNum”, defaultValue = “1”) for pagination
package com.tianju.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
@RequestMapping("/hello") // 二级目录
@ResponseBody
public String hello(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
System.out.println(pageNum);
System.out.println(pageSize);
return "Hello SpringMvc";
}
}
3.Rest style query xxx/search/mobile phone/white----xxx/search?item=mobile phone&color=white
Main points:
- Access path: @RequestMapping("/search/{item}/{color}");
- Get parameters: @PathVariable("item")
http://localhost/demo/search/mobilephone/red
package com.tianju.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.security.SignedObject;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
// http://localhost/demo/search/mobilephone/red
@RequestMapping("/search/{item}/{color}") // 二级目录
@ResponseBody
public String hello(@PathVariable("item") String item,
@PathVariable("color") String color){
System.out.println(item);
System.out.println(color);
return "Hello SpringMvc";
}
}
4. The backend uses object reception + array/collection
Main points:
- Objects can be used to receive data from the front end, and the mapping will be done automatically
- Arrays or collections can be passed
http://localhost/demo/add/user?username=peter&password=123&hobby=learn&hobby=game
package com.tianju.controller;
import com.tianju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.security.SignedObject;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
// http://localhost/demo/add/user?username=peter
// &password=123&hobby=learn&hobby=game
@RequestMapping("/add/user") // 二级目录
@ResponseBody
public String hello(User user){
System.out.println(user);
return "Hello SpringMvc";
}
}
5. Date processing, the default format is 2021/05/28, [to be continued]
Main points:
- By default, only dates in the format of 2021/05/28 can be sent
http://localhost/demo/date?birthday=2021/05/28
package com.tianju.controller;
import com.tianju.entity.User;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.security.SignedObject;
import java.util.Date;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
// http://localhost/demo/date?birthday=2021/05/28
@RequestMapping("/date") // 二级目录
@ResponseBody
public String hello(Date birthday){
System.out.println(birthday);
return "Hello SpringMvc";
}
}
400 exception, date format conversion failed
Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2021-5-28’; nested exception is java.lang.IllegalArgumentException]
6. How to get the request header, the value in the cookie, and the original request and response, etc.
Main points:
-
write what you need;
-
HttpServletRequest request,
-
HttpSession httpSession,
http://localhost/demo/set/session
http://localhost/demo/native
package com.tianju.controller;
import com.tianju.entity.User;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.SignedObject;
import java.util.Date;
/**
* controller层,
* 1.在容器中: @Controller
* 2.用来处理网络请求:即 @RequestMapping("/demo")
* 既可以放在类上:一级目录;
* 也可以在方法上:二级目录:http://localhost/demo/hello
*/
@Controller
@RequestMapping("/demo") // 一级目录
public class ResponseControllerDemo {
// http://localhost/demo/date?birthday=2021/05/28
@RequestMapping("/native") // 二级目录
@ResponseBody
public String hello(HttpServletRequest request,
HttpSession httpSession,
HttpServletResponse response,
@RequestHeader("Connection") String connection,
@CookieValue("JSESSIONID") String jsessionid){
// 1.request里面就可以获得session,之前servlet就是这样的
HttpSession session = request.getSession();
// 2.加上httpSession,也能获得;
Object username = httpSession.getAttribute("username");
System.out.println(username);
System.out.println(response);
System.out.println("----获取请求头里的connection------");
System.out.println(connection);
System.out.println(jsessionid);
return "Hello SpringMvc";
}
@RequestMapping("/set/session")
@ResponseBody
public String setSession(HttpSession session){
session.setAttribute("username", "peter");
System.out.println(session);
return "success";
}
}
Request header
to get connection and jsessionid
The server responds with Response—the backend sends content to the frontend
Need a package, front-end template engine, similar to jsp
<!-- 前端模板引擎,功能类似于jsp-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1. Respond to a Json + time display @JsonFormat [with pits]
Main points:
-
The response is json, add @ResponseBody;
-
For the time display problem, GMT+8 is required:
-
@JsonFormat(pattern = “yyyy-MM-DD hh:mm:ss”, timezone = “GMT+8”)
-
If a controller response is all json, @RestController can be used instead of @Controller and @ResponseBody
Note here, the date conversion format is wrong, DD should be changed to lowercase dd
date format conversion
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",timezone = "GMT+8")
private Date birthday;
controller's code
package com.tianju.controller;
import com.tianju.entity.ResData;
import com.tianju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Date;
/**
* 响应相关:1.响应json;2.响应页面
* 要点:
* 1.在容器@Controller;
* 2.路径;@RequestMapping("/resp");
* 3.如果是响应json,需要加@ResponseBody;
* 4.如果响应页面,则返回值是string
* 补充:如果一个controller响应都是json
* 则,@RestController代替 @Controller 和 @ResponseBody
*/
@Controller
@RequestMapping("/resp")
//@RestController // 等价于@Controller + @ResponseBody
public class ResponseControllerDemo {
@RequestMapping("/json")
@ResponseBody // 如果响应是json,必须加
public ResData respJson(){
User user = new User("peter", "123",
new Date(), Arrays.asList(new String[]{
"learn","movie"}));
return new ResData(200, "success", user);
}
}
You can not write responseBody, use @RestController
2. Respond to a page and return the value String
Main points:
- 1. The return value is string;
- 2. Responsebody cannot be added
The server responds to the html code and displays it on the front-end page
Access to files under resources can be modified, not recommended
access connection
http://localhost/resp/list
backend code
/**
* 响应一个页面
* @return list页面,会在前面拼 /templates,后面拼.html
* 最终访问到xxx/templates/opus/list.html
*/
@RequestMapping("/list")
public String respHtml(){
return "/opus/list";
}
2. Response page, ModelAndView and shared data [[${usename}]]
Main points:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
// 1.定义要跳转的页面,2.添加要共享的数据
ModelAndView mv = new ModelAndView("opus/list");
mv.addObject("username", "peter");
The first way: not recommended
The second method: this method will be used to share data in the future
Shared values are displayed to the frontend
@RequestMapping("/listAndData")
public ModelAndView respHtmlData(){
// 1.定义要跳转的页面,2.添加要共享的数据
ModelAndView mv = new ModelAndView("opus/list");
mv.addObject("username", "peter");
return mv;
}
3. If you want to handle it yourself, use void
Key points: no return value, use void
package com.tianju.controller;
import com.alibaba.fastjson.JSON;
import com.tianju.entity.ResData;
import com.tianju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
/**
* 响应相关:1.响应json;2.响应页面
* 要点:
* 1.在容器@Controller;
* 2.路径;@RequestMapping("/resp");
* 3.如果是响应json,需要加@ResponseBody;
* 4.如果响应页面,则返回值是string
* 补充:如果一个controller响应都是json
* 则,@RestController代替 @Controller 和 @ResponseBody
*/
@Controller
@RequestMapping("/resp")
//@RestController // 等价于@Controller + @ResponseBody
public class ResponseControllerDemo {
@RequestMapping("/json")
@ResponseBody // 如果响应是json,必须加
public ResData respJson(){
User user = new User("peter", "123",
new Date(), Arrays.asList(new String[]{
"learn","movie"}));
return new ResData(200, "success", user);
}
/**
* 响应一个页面
* @return list页面,会在前面拼 /templates,后面拼.html
* 最终访问到xxx/templates/opus/list.html
*/
@RequestMapping("/list")
public String respHtml(){
return "/opus/list";
}
@RequestMapping("/listAndData")
public ModelAndView respHtmlData(){
// 1.定义要跳转的页面,2.添加要共享的数据
ModelAndView mv = new ModelAndView("opus/list");
mv.addObject("username", "peter");
return mv;
}
/**
* 如果想自己处理,就用void
*/
@RequestMapping("/self")
public void test(HttpServletResponse response) throws IOException {
ResData resData = new ResData(200, "success", null);
response.getWriter().write(JSON.toJSONString(resData));
}
}
SpringMvc handles uploading files
1. Upload the file and save it to the local MultipartFile
Main points:
- 1. Submit with post + segment submission enctype="multipart/form-data";
- 2. Receive with MultipartFile to receive, you can get the name size, etc.;
- 3. Save to the local can use transferTo, or get the input stream processing;
You can get the picture, get the size of the picture, and process the size
Backend controller code
package com.tianju.controller;
import com.tianju.entity.ResData;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 上传文件:
* 要点:
* 1.前端怎么提交:
* 2.后端怎么接收:
* 3.接收后怎么处理:
*/
//@RestController // 等价于@Controller 和 @ResponseBody
@Controller
@RequestMapping("/file")
public class UploadController {
// 1.先到上传图片的页面
@RequestMapping("/uploadPage")
public String uploadPage(){
return "/opus/upload";
}
// 2.处理前端上传的图片
@RequestMapping("/upload")
@ResponseBody
public ResData uploadImg(MultipartFile headImg) throws IOException {
long size = headImg.getSize(); // 文件大小
String filename = headImg.getOriginalFilename(); // 文件名
System.out.println("上传的文件:"+filename+",文件大小"+size);
// 对文件进行处理
// (1)拿到输入流,然后保存到本地;以后也可能通过网络发送到其他地方
InputStream inputStream = headImg.getInputStream();
FileOutputStream outputStream = new FileOutputStream("D:/06/" + filename);
IOUtils.copy(inputStream, outputStream);
// 谁建的谁关
outputStream.close();
// (2)不用流直接存到本地文件中
headImg.transferTo(new File("D:\\620\\"+filename));
return new ResData(200, "ok", null);
}
}
Front-end upload.html page code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 提交方法必须是post,并且用分段提交 -->
<form action="/file/upload"
method="post"
enctype="multipart/form-data">
<input type="file" name="headImg">
<input type="submit" value="提交">
</form>
</body>
</html>
2. The problem of uploading files with the same name being overwritten—rename with uuid
Main points:
- 1. Rename with uuid, remove - from uuid, replace method;
- 2. Get the suffix of the uploaded file int i = originalFilename.lastIndexOf(“.”); substring(i);
- 3. Save to local
package com.tianju.controller;
import com.tianju.entity.ResData;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
/**
* 上传文件:
* 要点:
* 1.前端怎么提交:
* 2.后端怎么接收:
* 3.接收后怎么处理:
*/
//@RestController // 等价于@Controller 和 @ResponseBody
@Controller
@RequestMapping("/file")
public class UploadController {
// 1.先到上传图片的页面
@RequestMapping("/uploadPage")
public String uploadPage(){
return "/opus/upload";
}
// 2.处理前端上传的图片
@RequestMapping("/upload")
@ResponseBody
public ResData uploadImg(MultipartFile headImg) throws IOException {
long size = headImg.getSize(); // 文件大小
String originalFilename = headImg.getOriginalFilename(); // 文件名
System.out.println("上传的文件:"+originalFilename+",文件大小"+size);
// 对文件进行处理 (2)不用流直接存到本地文件中
// 获得uuid,并把中间-去掉
String randomStr = UUID.randomUUID().toString().replace("-", "");
// 获取上传文件的后缀
int i = originalFilename.lastIndexOf(".");
String suffix = originalFilename.substring(i, originalFilename.length());
headImg.transferTo(new File("D:\\620\\"+randomStr+suffix));
return new ResData(200, "ok", null);
}
}
3. Local computer pictures for display—static resource mapping—protocol file:
Main points:
- 1. Create a new configuration class to implement the WebMvcConfigurer interface;
- 2. addResourceHandlers method, local file protocol file:
Local file protocol, /** indicates that subdirectories can also be found
Web page access to local images
springMvcConfig.java file
package com.tianju.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* springMvc的配置类,spring的相关配置都在这里
* 要点:
* 1.是配置类;@Configuration
* 2.是springMvc的配置类:implements WebMvcConfigurer
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
/**
* 能够把服务器上的一个目录,映射成一个路径,http可以直接访问到
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 在浏览器上,如果访问/bookImg/1.jpg,springMvc就去D:\620\1.jpg找对应的文件
// /bookimg/** 表示子目录下的文件也能找到
registry.addResourceHandler("/bookimg/**")
.addResourceLocations("file:D:\\620\\");
}
}
4. Put the path of the uploaded file in the spring configuration file and get @Value(“${imgLocation}”)
Main points:
- Configure in the application.yml file;
- Get it through @Value("${imgLocation}";
application.yml file
server:
port: 80
## 图片上传的路径
imgLocation: D:\\620\\
Other file acquisition:
package com.tianju.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* springMvc的配置类,spring的相关配置都在这里
* 要点:
* 1.是配置类;@Configuration
* 2.是springMvc的配置类:implements WebMvcConfigurer
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Value("${imgLocation}")
private String imgLocation;
/**
* 能够把服务器上的一个目录,映射成一个路径,http可以直接访问到
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 在浏览器上,如果访问/bookImg/1.jpg,springMvc就去D:\620\1.jpg找对应的文件
// /bookimg/** 表示子目录下的文件也能找到
registry.addResourceHandler("/bookimg/**")
.addResourceLocations("file:"+imgLocation);
}
}
Summarize
1.Model View Controller model view controller;
2.idea builds a springWeb project, a common project, inheriting a parent, the main startup class @SpringBootApplication, application.yml configuration file;
3. Browser request @RequestMapping("/demo"), It can be used on classes, methods, first-level and second-level directories;
4. Request parameter @RequestParam(value = "pageNum", defaultValue = "1"), which can be used on pagination;
5. Request: query xxx/search/mobile /white, @RequestMapping("/search/{item}/{color}")----@PathVariable("item");
6. Request: get request, parameter plus HttpServletRequest request;
7. Server response, response Page, respond to json, handle it yourself;
8. Respond to JSON, @ResponseBody, time format, @JsonFormat(pattern = "yyyy-MM-DD hh:mm:ss", timezone = "GMT+8"); 9. Response
page : The return value is string, and @ResponseBody cannot be added;
10. Response page with some data: ModelAndView and shared data [[${usename}]];
11. Upload file MultipartFile reception, segmented post submission: enctype="multipart/form -data";
12. Static resource mapping: springMvcConfig configuration class @Configuration, implement interface WebMvcConfigurer, addResourceHandlers method, local file protocol file:/;
13. Get the value in the application.yml file, use @Value(" $ {imgLocation}";