目次
- 導き出す
- 基礎知識: 3 層アーキテクチャと MVC
- springWebプロジェクトIDEA構築
- SpringMvc ブラウザ リクエストの予備的
- ブラウザがパラメータを渡すリクエストをリクエストする方法
-
- 1. 基本的なデータ型と文字列
- 2. 送信名、受信はユーザー名、@RequestParam(value = "name")
- 2. [アプリケーション] ページングは @RequestParam(value = "pageNum",defaultValue = "1") を使用できます
- 3.残りのスタイルクエリxxx/search/mobilephone/white----xxx/search?item=mobilephone&color=white
- 4. バックエンドはオブジェクト受信 + 配列/コレクションを使用します
- 5. 日付処理、デフォルトの形式は 2021/05/28、[続く]
- 6. リクエストヘッダー、Cookie内の値、元のリクエストとレスポンスなどの取得方法
- サーバーが Response に応答します --- バックエンドがコンテンツをフロントエンドに送信します
- SpringMvc はファイルのアップロードを処理します
- 要約する
導き出す
mvc とは何ですか、springMvc とは何ですか、springWeb プロジェクトのビルド方法、
springMvc でのリクエストとレスポンスの送信方法、および応答方法
SpringMvc 処理ファイル関連: ファイルのアップロード、uuid の名前変更、静的リソース マッピング、yaml 設定パス、予備の Spring 設定ファイル。
基礎知識: 3 層アーキテクチャと MVC
1. 3層アーキテクチャ
- プレゼンテーション (ビュー) レイヤー: WEB レイヤー。クライアントとのデータ対話に使用されます。サーブレットコントローラー
- ビジネス層:企業独自のビジネスロジックを扱うサービス
- 永続層: データベースの操作に使用される dao-mapper
2.MVCモデル
-
MVC の正式名は Model View Controller モデル ビュー コントローラーであり、それぞれの部分が独自の役割を果たします。
-
モデル: データ モデル、JavaBean クラス、データのカプセル化に使用されます。
-
ビュー: ユーザーにデータを表示するために使用される JSP および HTML を指します Android-http、Apple、アプレット
-
コントローラー: ユーザーリクエストを受信するために使用され、プロセス全体のコントローラーです。データの検証等に利用されます。
springWebプロジェクトIDEA構築
1. 新しい通常の Maven プロジェクトを作成します
2. パッケージ、pom.xml ファイルをインポートします。
(1) 親を継承する
<!-- 继承一个父-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
(2) Webプロジェクト+フロントエンドテンプレートエンジンのパッケージ
<!-- 做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) 完成した 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.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. メインのスタートアップ クラス Main.java ファイル @SpringBootApplication を作成します。
要点:
- これは spingMvc の構成クラスです: @SpringBootApplication;
- 開始: SpringApplication.run(Main.class);
- ディレクトリ階層の問題、および同じレベルの他のディレクトリの問題。
Main.java ファイル
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. application.yml ファイルのスプリング構成ファイルを作成します。
要点:
- ファイル名はapplication.ymlです。
- 色が黄色の場合はスペースが必要です
server:
port: 80
5. 開始し、main.java を実行して開始します。
SpringMvc ブラウザ リクエストの予備的
1. springMvc について知る @RequestMapping("/demo")
要点:
- 1. コントローラーはコンテナー内にある必要があります: @Controller
- 2. ブラウザリクエストの処理に使用されます: @RequestMapping(“/demo”)
- @RequestMapping("/demo") は、クラスまたはメソッド (第 1 レベルと第 2 レベルのディレクトリ) に置くことができます。
ResponseControllerDemo.java ファイル
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. @RequestMapping から派生
@PostMapping,@GetMapping,@DeleteMapping,@PutMapping
@RequestMapping
@PostMapping(“/hello”)
@GetMapping
@DeleteMapping
@PutMapping
405 例外: サーバーはポストのみを処理でき、ブラウザは get メソッドを要求します
ブラウザがパラメータを渡すリクエストをリクエストする方法
1. 基本的なデータ型と文字列
要点:
- 文字列が渡されない場合、デフォルトは空の文字列です。
- 整数は渡されません。デフォルトは 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. 送信名、受信はユーザー名、@RequestParam(value = "name")
要点:
-
デフォルトでは、値を渡す必要があり、値が渡されない場合は 400 例外が報告されます。
-
これを渡したくない場合は、required=false を追加します。
-
デフォルト値、defaultValue="admin"; を指定することもできます [アプリケーション: ページングの場合、デフォルトは最初のページであり、デフォルトは 1 ページあたり 10 データです]
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 例外、追加 @RequestParam(value = "name") は値を渡す必要があります
400 例外、バックエンドの型は整数、フロントエンドは文字列で、変換は失敗します
2. 【応用】ページネーションに @RequestParam(value = “pageNum”,defaultValue = “1”) を使用できます
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.残りのスタイルクエリxxx/search/mobilephone/white----xxx/search?item=mobilephone&color=white
要点:
- アクセスパス: @RequestMapping("/search/{item}/{color}");
- パラメータの取得: @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. バックエンドはオブジェクト受信 + 配列/コレクションを使用します
要点:
- オブジェクトを使用してフロントエンドからデータを受信でき、マッピングは自動的に行われます。
- 配列またはコレクションを渡すことができます
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. 日付処理、デフォルトの形式は 2021/05/28、[続く]
要点:
- デフォルトでは、2021/05/28 の形式の日付のみ送信できます
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 例外、日付形式の変換に失敗しました
値「2021-5-28」の型 [java.lang.String] から型 [java.util.Date] への変換に失敗しました。ネストされた例外は java.lang.IllegalArgumentException です]
6. リクエストヘッダー、Cookie内の値、元のリクエストとレスポンスなどの取得方法
要点:
-
必要なことを書きます。
-
HttpServletRequest リクエスト、
-
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";
}
}
接続と jsessionid を取得するためのリクエスト ヘッダー
サーバーは Response で応答します。バックエンドはコンテンツをフロントエンドに送信します。
JSP に似たパッケージ、フロントエンド テンプレート エンジンが必要
<!-- 前端模板引擎,功能类似于jsp-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1. Json + 時間表示 @JsonFormat [ピットあり] に応答します
要点:
-
応答は json であり、@ResponseBody を追加します。
-
時刻表示の問題では、GMT+8 が必要です。
-
@JsonFormat(パターン = “yyyy-MM-DD hh:mm:ss”、タイムゾーン = “GMT+8”)
-
コントローラーの応答がすべて json の場合、@Controller と @ResponseBody の代わりに @RestController を使用できます。
ここで、日付の変換形式が間違っていることに注意してください。DD は小文字の dd に変更する必要があります。
日付形式の変換
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",timezone = "GMT+8")
private Date birthday;
コントローラーのコード
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);
}
}
responseBody を記述することはできません。@RestController を使用してください
2. ページに応答し、値 String を返します。
要点:
- 1. 戻り値は文字列です。
- 2. レスポンスボディを追加できない
サーバーは HTML コードに応答し、それをフロントエンド ページに表示します。
リソースの下のファイルへのアクセスは変更可能ですが、推奨されません
アクセス接続
http://localhost/resp/list
バックエンドコード
/**
* 响应一个页面
* @return list页面,会在前面拼 /templates,后面拼.html
* 最终访问到xxx/templates/opus/list.html
*/
@RequestMapping("/list")
public String respHtml(){
return "/opus/list";
}
2. 応答ページ、ModelAndView、共有データ [[${usename}]]
要点:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
// 1.定义要跳转的页面,2.添加要共享的数据
ModelAndView mv = new ModelAndView("opus/list");
mv.addObject("username", "peter");
最初の方法: 推奨されません
2 番目の方法: この方法は将来データを共有するために使用されます。
共有された値はフロントエンドに表示されます
@RequestMapping("/listAndData")
public ModelAndView respHtmlData(){
// 1.定义要跳转的页面,2.添加要共享的数据
ModelAndView mv = new ModelAndView("opus/list");
mv.addObject("username", "peter");
return mv;
}
3. 自分で処理したい場合は void を使用します
キーポイント: 戻り値なし、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 はファイルのアップロードを処理します
1. ファイルをアップロードし、ローカルの MultipartFile に保存します。
要点:
- 1. ポスト + セグメント送信で送信 enctype="multipart/form-data";
- 2. MultipartFile で受信して、名前のサイズなどを取得できます。
- 3. ローカルに保存するには、transferTo を使用するか、入力ストリーム処理を取得します。
写真を取得し、写真のサイズを取得し、サイズを加工することができます
バックエンドコントローラーのコード
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);
}
}
フロントエンドのupload.htmlページのコード
<!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. 同じ名前のファイルをアップロードすると上書きされる問題 - uuid で名前を変更する
要点:
- 1. uuid で名前を変更し、uuid から - を削除し、メソッドを置き換えます。
- 2. アップロードされたファイルのサフィックスを取得します int i =originalFilename.lastIndexOf(“.”); substring(i);
- 3. ローカルに保存
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. 表示用のローカル コンピュータの画像 - 静的リソース マッピング - プロトコル ファイル:
要点:
- 1. WebMvcConfigurer インターフェイスを実装する新しい構成クラスを作成します。
- 2. addResourceHandlers メソッド、ローカル ファイル プロトコル ファイル:
ローカル ファイル プロトコル、/** はサブディレクトリも見つかることを示します
Web ページからローカル画像へのアクセス
springMvcConfig.java ファイル
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. アップロードしたファイルのパスを Spring 構成ファイルに入力し、 @Value(“${imgLocation}”) を取得します
要点:
- application.yml ファイルで構成します。
- @Value("${imgLocation}"; を通じて取得します。
application.yml ファイル
server:
port: 80
## 图片上传的路径
imgLocation: D:\\620\\
その他のファイル取得:
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);
}
}
要約する
1.Model View Controller モデル ビュー コントローラー;
2.idea は、親、メイン起動クラス @SpringBootApplication、application.yml 設定ファイルを継承して、共通プロジェクトである springWeb プロジェクトを構築します; 3.
ブラウザー リクエスト @RequestMapping("/demo") , クラス、メソッド、第 1 レベルおよび第 2 レベルのディレクトリで使用できます;
4. ページングで使用できるリクエスト パラメーター @RequestParam(value = "pageNum",defaultValue = "1");
5. リクエスト: query xxx/search/mobile /white, @RequestMapping("/search/{item}/{color}")----@PathVariable("item"); 6. リクエスト: リクエストの取得、パラメータと HttpServletRequest リクエスト
;
7 . サーバー応答、応答ページ、json への応答、自分で処理;
8. JSON への応答、@ResponseBody、時刻形式、@JsonFormat(pattern = "yyyy-MM-DD hh:mm:ss"、timezone = "GMT+ 8"); 9. レスポンス
ページ : 戻り値は文字列のため、@ResponseBody は追加できません;
10. データを含むレスポンスページ: ModelAndView と共有データ [[${usename}]];
11. アップロードファイル MultipartFile 受付、セグメント化された投稿送信: enctype="multipart/form -data";
12. 静的リソース マッピング: springMvcConfig 設定クラス @Configuration、実装インターフェイス WebMvcConfigurer、addResourceHandlers メソッド、ローカル ファイル プロトコル file:/; 13.
application.yml ファイル内の値を取得し、@Value(" $ {imgLocation}"; を使用します)