SpringBoot_11 開發(fā)Web應(yīng)用程序

開發(fā)Web應(yīng)用程序


Spring Boot非常適合Web應(yīng)用程序開發(fā)。您可以使用嵌入式Tomcat,Jetty,Undertow或Netty創(chuàng)建自包含的HTTP服務(wù)器。大多數(shù)Web應(yīng)用程序使用該spring-boot-starter-web模塊快速啟動(dòng)和運(yùn)行。您還可以選擇使用該spring-boot-starter-webflux模塊構(gòu)建響應(yīng)式Web應(yīng)用程序 。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Spring Web MVC框架


Spring Web MVC是一個(gè)豐富的“模型視圖控制器” Web框架。簡(jiǎn)稱Spring MVC且允許您綁定特殊的@Controller或@RestControllerbean注解來處理傳入的HTTP請(qǐng)求??刂破髦械姆椒ㄍㄟ^使用@RequestMapping注解映射到HTTP 。

以下代碼顯示了@RestController注解為JSON數(shù)據(jù)提供服務(wù)的典型代碼:

@RestController
@RequestMapping(value="/users")
public class MyRestController {

    @RequestMapping(value="/{user}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long user) {
        // ...
    }

    @RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
    List<Customer> getUserCustomers(@PathVariable Long user) {
        // ...
    }

    @RequestMapping(value="/{user}", method=RequestMethod.DELETE)
    public User deleteUser(@PathVariable Long user) {
        // ...
    }

}

Spring MVC自動(dòng)配置


自動(dòng)配置在Spring的默認(rèn)值之上添加很多功能,例如:

  • 靜態(tài)index.html支持
  • 自定義Favicon支持
  • 支持提供靜態(tài)資源

靜態(tài)內(nèi)容


默認(rèn)情況下,Spring Boot從資源根目錄或類根目錄或src/main/resources/static目錄中提供靜態(tài)內(nèi)容.

歡迎頁(yè)面


Spring Boot支持靜態(tài)和模板化歡迎頁(yè)面。在src/main/resources/static目錄下查找index文件或模板。如果找到任何一個(gè),它將自動(dòng)用作應(yīng)用程序的歡迎頁(yè)面

自定義Favicon


Spring Boot 在配置的靜態(tài)內(nèi)容位置和類路徑的根(按此順序)中查找favicon.ico 。如果存在這樣的文件,它將自動(dòng)用作應(yīng)用程序的展示圖標(biāo)。

跨源資源共享


在Spring Boot應(yīng)用程序中使用帶有@CrossOrigin注解的控制器方法且不需要任何其他特定配置就可以實(shí)現(xiàn)跨域

其他方式


  • HttpMessageConverters
  • 自定義JSON序列化程序和反序列化程序
  • MessageCodesResolver
  • 路徑匹配和內(nèi)容協(xié)商
  • ConfigurableWebBindingInitializer
  • 模板引擎
  • 錯(cuò)誤處理
  • 映射Spring MVC之外的錯(cuò)誤頁(yè)面
  • Spring HATEOAS
  • Spring WebFlux框架
  • Spring WebFlux自動(dòng)配置
  • 帶有HttpMessageReaders和HttpMessageWriters的HTTP編解碼器
  • 嵌入式Servlet容器支持
  • 程序化定制
  • 嵌入式Reactive Server支持
  • Reactive Server資源配置

下面的內(nèi)容出自Spring Web MVC

帶注解的控制器


Spring MVC提供基于注解的編程模型,其中@Controller和 @RestController組件使用注釋來表達(dá)請(qǐng)求映射,請(qǐng)求輸入,異常處理等。帶注解的控制器具有靈活的方法簽名,不必?cái)U(kuò)展基類,也不必實(shí)現(xiàn)特定的接口。以下示例顯示了由注釋定義的控制器:

get http://localhost:8080/hello?par=test
@Controller
public class HelloController {

    @GetMapping("/hello")
    public String handle(HttpServletRequest request, String par) {
        // others
        return "index";
    }
}

文件上傳下載:最簡(jiǎn)化


@RestController
public class FileUploadController {

    @Value("${file.base.path}")
    String filePath;
    
    @PostMapping("/fileUp")
    public String getName(String fileName, MultipartFile fileUpload){
        String uid = UUID.randomUUID().toString().replace('-','x');
        if ( fileUpload.isEmpty() == false) {
            try {
                Path basePath = Paths.get(filePath+"file/");
                if(Files.notExists(basePath)) Files.createDirectory(basePath);
                fileUpload.transferTo(new File(filePath+"file/"+uid+fileName));
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }else{
            return "null";
        }
        return "filePath/"+uid+fileName;
    } 
    @GetMapping("/fileLoad")
    public void handleFormUpload(HttpServletResponse response) {
        try{
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=name.txt");
            Files.copy(Paths.get(filePath+"file/name.txt"),outputStream );
            outputStream.flush();
            outputStream.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

transferTo(File):轉(zhuǎn)存文件
List<MultipartFile>:接收多個(gè)文件上傳
中文亂碼:new String(name.getBytes("UTF-8"),"iso-8859-1");
application/x-download:設(shè)置內(nèi)容類型為下載類型
Content-Disposition,attachment;filename=name:設(shè)置文件下載提示和文件名

重定向


redirect:原請(qǐng)求數(shù)據(jù)丟失

@Controller
public class HelloController {
    @GetMapping("/red")
    public String toRedict(HttpServletResponse response) {
        return "redirect:/boss.html";
    }
}

轉(zhuǎn)發(fā)


forward:原數(shù)據(jù)還在

@Controller
public class HelloController {
    @GetMapping("/for")
    public String toForwerd(HttpServletResponse response) {
        return "forward:/client.html";
    }
}

重定向和轉(zhuǎn)發(fā)的頁(yè)面都是在資源下的static靜態(tài)目錄下的html頁(yè)面,斜杠開頭代表根目錄開始

請(qǐng)求映射


你可以使用 @RequestMapping注解將請(qǐng)求映射到控制器方法上。它具有各種屬性,可通過URL,HTTP方法,請(qǐng)求參數(shù),標(biāo)頭和媒體類型進(jìn)行匹配。您可以在類級(jí)別使用它來表示共享映射,或者在方法級(jí)別使用它來縮小到特定的端點(diǎn)映射。

還有HTTP方法特定的快捷方式變體@RequestMapping(默認(rèn)情況下,它與所有HTTP方法匹配):
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
您可以使用以下全局模式和通配符映射請(qǐng)求:

  • ?匹配一個(gè)字符
  • *匹配路徑段中的零個(gè)或多個(gè)字符
  • **匹配零個(gè)或多個(gè)路徑段

控制器常用方法參數(shù)


控制器方法請(qǐng)求參數(shù) 描述
javax.servlet.ServletRequest, javax.servlet.ServletResponse 選擇任何特定的請(qǐng)求或響應(yīng)類型-例如ServletRequest,HttpServletRequest或Spring的MultipartRequest,MultipartHttpServletRequest。
javax.servlet.http.HttpSession 強(qiáng)制進(jìn)行會(huì)話。因此,這種論點(diǎn)永遠(yuǎn)不會(huì)null。請(qǐng)注意,會(huì)話訪問不是線程安全的。如果允許多個(gè)請(qǐng)求同時(shí)訪問會(huì)話,請(qǐng)考慮將RequestMappingHandlerAdapter實(shí)例的synchronizeOnSession標(biāo)志設(shè)置為 true。
HttpMethod 請(qǐng)求的HTTP方法
@PathVariable 用于訪問URI模板變量
@RequestParam 用于訪問Servlet請(qǐng)求參數(shù),包括多部分文件。參數(shù)值將轉(zhuǎn)換為聲明的方法參數(shù)類型。請(qǐng)注意,@RequestParam對(duì)于簡(jiǎn)單參數(shù)值,使用是可選的
@RequestHeader 用于訪問請(qǐng)求標(biāo)頭。標(biāo)頭值將轉(zhuǎn)換為聲明的方法參數(shù)類型。
@CookieValue 用于訪問cookie。Cookie值將轉(zhuǎn)換為聲明的方法參數(shù)類型。
@RequestBody 用于訪問HTTP請(qǐng)求正文。通過使用HttpMessageConverter實(shí)現(xiàn)將正文內(nèi)容轉(zhuǎn)換為聲明的方法參數(shù)類型。
HttpEntity<B> 用于訪問請(qǐng)求標(biāo)頭和正文。身體轉(zhuǎn)換為HttpMessageConverter
@SessionAttribute 用于訪問任何會(huì)話屬性,與由于類級(jí)@SessionAttributes聲明而存儲(chǔ)在會(huì)話中的模型屬性相反。
@RequestAttribute 用于訪問請(qǐng)求屬性。

控制器常用方法返回值


控制器常用方法返回值 描述
@ResponseBody 返回值通過HttpMessageConverter實(shí)現(xiàn)轉(zhuǎn)換并寫入響應(yīng)。
HttpEntity<B>ResponseEntity<B> 指定完整響應(yīng)(包括HTTP標(biāo)頭和正文)的返回值將通過HttpMessageConverter實(shí)現(xiàn)進(jìn)行轉(zhuǎn)換并寫入響應(yīng)。
HttpHeaders 用于返回帶標(biāo)題且沒有正文的響應(yīng)。
String 要使用ViewResolver實(shí)現(xiàn)解析的視圖名稱,并與隱式模型一起使用 - 通過命令對(duì)象和@ModelAttribute方法確定。處理程序方法還可以通過聲明Model參數(shù)以編程方式豐富模型
View View實(shí)例以使用用于與所述隱式模型一起渲染-通過命令對(duì)象和確定@ModelAttribute方法。處理程序方法還可以通過聲明Model參數(shù)以編程方式豐富模型
java.util.Map, org.springframework.ui.Model 要添加到隱式模型的屬性,通過RequestToViewNameTranslator隱式確定視圖名稱。
@ModelAttribute 要添加到模型的屬性,通過a隱式確定視圖名稱RequestToViewNameTranslator。請(qǐng)注意,這@ModelAttribute是可選的。請(qǐng)參見本表末尾的“任何其他返回值”。
ModelAndView 要使用的視圖和模型屬性,以及(可選)響應(yīng)狀態(tài)。
void 具有void返回類型(或null返回值)的方法被認(rèn)為已完全處理響應(yīng)(如果它還具有a ServletResponse,OutputStream參數(shù)或@ResponseStatus注釋)。如果控制器已進(jìn)行正檢查ETaglastModified時(shí)間戳檢查,也是如此,如果以上都不是,則void返回類型還可以指示REST控制器的“無響應(yīng)主體”或HTML控制器的默認(rèn)視圖名稱選擇。

URI變量


您可以在類和方法級(jí)別聲明URI變量,如以下示例所示:

@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {

    @GetMapping("/pets/{petId}")
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...
    }
}

URI變量會(huì)自動(dòng)轉(zhuǎn)換為適當(dāng)?shù)念愋停蛘逿ypeMismatchException 被引發(fā)。簡(jiǎn)單類型(int,long,Date,等)默認(rèn)支持,你可以注冊(cè)任何其它數(shù)據(jù)類型的支持。

您可以顯式命名URI變量(例如,@PathVariable("customId"))

語(yǔ)法{varName:regex}聲明一個(gè)URI變量,其正則表達(dá)式的語(yǔ)法為{varName:regex}。例如,給定URL "/spring-web-3.0.5 .jar",以下方法提取名稱,版本和文件擴(kuò)展名:

@GetMapping("/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
public void handle(@PathVariable String name, @PathVariable String version, @PathVariable String ext) {
    // ...
}

URI路徑模式還可以具有嵌入式${…?}占位符,這些占位符在啟動(dòng)時(shí)通過使用PropertyPlaceHolderConfigurer針對(duì)本地,系統(tǒng),環(huán)境和其他屬性源來解析。例如,您可以使用此參數(shù)來基于某些外部配置參數(shù)化基本URL。

使用consumes屬性通過內(nèi)容類型縮小映射范圍


@PostMapping(path = "/pets", consumes = "application/json") 
public void addPet(@RequestBody Pet pet) {
    // ...
}

該consumes屬性還支持否定表達(dá)式 - 例如,!text/plain表示除了以外的任何內(nèi)容類型text/plain

對(duì)應(yīng)關(guān)系


@GetMapping對(duì)應(yīng)@RequestMapping(method=HttpMethod.GET)
@PostMapping,@PutMapping,@DeleteMapping,和@PatchMapping等都有此對(duì)應(yīng)

@RequestParam,@RequestHeader,@PathVariable,@MatrixVariable,和@CookieValue)可以要求類型轉(zhuǎn)換如果參數(shù)被聲明為比其它的東西String。

對(duì)于此類情況,將根據(jù)配置的轉(zhuǎn)換器自動(dòng)應(yīng)用類型轉(zhuǎn)換

@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) { 
    //...
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容