javascript
Spring MVC快速入门
今天給大家介紹一下Spring MVC,讓我們學習一下如何利用Spring MVC快速的搭建一個簡單的web應用。
環境準備
- 一個稱手的文本編輯器(例如Vim、Emacs、Sublime Text)或者IDE(Eclipse、Idea Intellij)
- Java環境(JDK 1.7或以上版本)
- Maven 3.0+(Eclipse和Idea IntelliJ內置,如果使用IDE并且不使用命令行工具可以不安裝)
一個最簡單的Web應用
使用Spring Boot框架可以大大加速Web應用的開發過程,首先在Maven項目依賴中引入spring-boot-starter-web:
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.tianmaying</groupId><artifactId>spring-web-demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-web-demo</name><description>Demo project for Spring WebMvc</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.2.5.RELEASE</version><relativePath/></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>接下來創建src/main/java/Application.java:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@SpringBootApplication @RestController public class Application {@RequestMapping("/")public String greeting() {return "Hello World!";}public static void main(String[] args) {SpringApplication.run(Application.class, args);} }運行應用:mvn spring-boot:run或在IDE中運行main()方法,在瀏覽器中訪問http://localhost:8080,Hello World!就出現在了頁面中。只用了區區十幾行Java代碼,一個Hello World應用就可以正確運行了,那么這段代碼究竟做了什么呢?我們從程序的入口SpringApplication.run(Application.class, args);開始分析:
SpringApplication是Spring Boot框架中描述Spring應用的類,它的run()方法會創建一個Spring應用上下文(Application Context)。另一方面它會掃描當前應用類路徑上的依賴,例如本例中發現spring-webmvc(由 spring-boot-starter-web傳遞引入)在類路徑中,那么Spring Boot會判斷這是一個Web應用,并啟動一個內嵌的Servlet容器(默認是Tomcat)用于處理HTTP請求。
Spring WebMvc框架會將Servlet容器里收到的HTTP請求根據路徑分發給對應的@Controller類進行處理,@RestController是一類特殊的@Controller,它的返回值直接作為HTTP Response的Body部分返回給瀏覽器。
@RequestMapping注解表明該方法處理那些URL對應的HTTP請求,也就是我們常說的URL路由(routing),請求的分發工作是有Spring完成的。例如上面的代碼中[http://localhost:8080/](http://localhost:8080/)根路徑就被路由至greeting()方法進行處理。如果訪問[http://localhost:8080/hello](http://localhost:8080/hello),則會出現404 Not Found錯誤,因為我們并沒有編寫任何方法來處理/hello請求。
使用@Controller實現URL路由
現代Web應用往往包括很多頁面,不同的頁面也對應著不同的URL。對于不同的URL,通常需要不同的方法進行處理并返回不同的內容。
匹配多個URL
@RestController public class Application {@RequestMapping("/")public String index() {return "Index Page";}@RequestMapping("/hello")public String hello() {return "Hello World!";} }@RequestMapping可以注解@Controller類:
@RestController @RequestMapping("/classPath") public class Application {@RequestMapping("/methodPath")public String method() {return "mapping url is /classPath/methodPath";} }method方法匹配的URL是/classPath/methodPath"。
提示
可以定義多個@Controller將不同URL的處理方法分散在不同的類中
URL中的變量——PathVariable
在Web應用中URL通常不是一成不變的,例如微博兩個不同用戶的個人主頁對應兩個不同的URL: [鄧金全的微博_微博](鄧金全的微博_微博),[http://weibo.com/user2](http://weibo.com/user2)。我們不可能對于每一個用戶都編寫一個被@RequestMapping注解的方法來處理其請求,Spring MVC提供了一套機制來處理這種情況:
@RequestMapping("/users/{username}") public String userProfile(@PathVariable("username") String username) {return String.format("user %s", username); }@RequestMapping("/posts/{id}") public String post(@PathVariable("id") int id) {return String.format("post %d", id); }在上述例子中,URL中的變量可以用{variableName}來表示,同時在方法的參數中加上@PathVariable("variableName"),那么當請求被轉發給該方法處理時,對應的URL中的變量會被自動賦值給被@PathVariable注解的參數(能夠自動根據參數類型賦值,例如上例中的int)。
支持HTTP方法
對于HTTP請求除了其URL,還需要注意它的方法(Method)。例如我們在瀏覽器中訪問一個頁面通常是GET方法,而表單的提交一般是POST方法。@Controller中的方法同樣需要對其進行區分:
@RequestMapping(value = "/login", method = RequestMethod.GET) public String loginGet() {return "Login Page"; }@RequestMapping(value = "/login", method = RequestMethod.POST) public String loginPost() {return "Login Post Request"; }模板渲染
在之前所有的@RequestMapping注解的方法中,返回值字符串都被直接傳送到瀏覽器端并顯示給用戶。但是為了能夠呈現更加豐富、美觀的頁面,我們需要將HTML代碼返回給瀏覽器,瀏覽器再進行頁面的渲染、顯示。
一種很直觀的方法是在處理請求的方法中,直接返回HTML代碼,但是這樣做的問題在于——一個復雜的頁面HTML代碼往往也非常復雜,并且嵌入在Java代碼中十分不利于維護。更好的做法是將頁面的HTML代碼寫在模板文件中,渲染后再返回給用戶。為了能夠進行模板渲染,需要將@RestController改成@Controller:
import org.springframework.ui.Model;@Controller public class HelloController {@RequestMapping("/hello/{name}")public String hello(@PathVariable("name") String name, Model model) {model.addAttribute("name", name);return "hello"} }在上述例子中,返回值"hello"并非直接將字符串返回給瀏覽器,而是尋找名字為hello的模板進行渲染,我們使用Thymeleaf模板引擎進行模板渲染,需要引入依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>接下來需要在默認的模板文件夾src/main/resources/templates/目錄下添加一個模板文件hello.html:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head><title>Getting Started: Serving Web Content</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body><p th:text="'Hello, ' + ${name} + '!'" /> </body> </html>th:text="'Hello, ' + ${name} + '!'"也就是將我們之前在@Controller方法里添加至Model的屬性name進行渲染,并放入<p>標簽中(因為th:text是<p>標簽的屬性)。模板渲染還有更多的用法,請參考Thymeleaf官方文檔。
處理靜態文件
瀏覽器頁面使用HTML作為描述語言,那么必然也脫離不了CSS以及JavaScript。為了能夠瀏覽器能夠正確加載類似/css/style.css, /js/main.js等資源,默認情況下我們只需要在src/main/resources/static目錄下添加css/style.css和js/main.js文件后,Spring MVC能夠自動將他們發布,通過訪問/css/style.css, /js/main.js也就可以正確加載這些資源。
更多文章請訪問天碼營網站
作者:David
鏈接:https://zhuanlan.zhihu.com/p/20676923
來源:知乎
總結
以上是生活随笔為你收集整理的Spring MVC快速入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的VIM配置及说明【K-VIM】
- 下一篇: 你必须学会的Git入门基本操作