[Spring入門學習筆記][建立網站URL]

設計網站的URL

現代的Web站點都會設計一套擁有明確意義,方便用戶記憶的URL,不管是域名仍是路徑,以天碼營爲例:html

在HTML和CSS的學習中,咱們建立了我的博客網站的基本頁面,若是須要將他們放在Internet中讓其餘人能夠訪問,就必須爲它們設計一套URL,如今假設咱們的網站經過http://localhost:8080/能夠訪問:web

定義URL處理方法

在Spring WebMVC框架中,使用@RequestMapping註解能夠將URL與處理方法綁定起來,例如:spring

@Controller
public class IndexController {

    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "index";
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }
}

 

IndexController類中的兩個方法都被@RequestMapping註解,當應用程序運行後,在瀏覽器中訪問http://localhost:8080/,請求會被Spring MVC框架分發到index()方法進行處理。同理,http://localhost:8080/hello會交給hello()方法進行處理。瀏覽器

@ResponseBody註解表示處理函數直接將函數的返回值傳回到瀏覽器端顯示。同時,不要忘記給IndexController類加上@Controller註解。markdown

@RequestMapping註解一樣能夠加在類上:app

@Controller
@RequestMapping("/posts")
public class AppController {

    @RequestMapping("/create")
    public String create() {
        return "mapping url is /posts/create";
    }
}

 

create()綁定的URL路徑是/posts/create。框架

URL變量

在Web應用中URL一般不是一成不變的,例如微博兩個不一樣用戶的我的主頁對應兩個不一樣的URL: http://weibo.com/user1http://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)。spring-boot

返回HTML

在以前全部的@RequestMapping註解的方法中,返回值字符串都被直接傳送到瀏覽器端並顯示給用戶。可是爲了可以呈現更加豐富、美觀的頁面,咱們須要將HTML代碼返回給瀏覽器,瀏覽器再進行頁面的渲染、顯示。 一種很直觀的方法是在處理請求的方法中,直接返回HTML代碼:post

@RequestMapping("/posts/{id}")
public String post(@PathVariable("id") int id) {
    return "<html><head><title>Title</title></head><body><h2>This is a Post</h2><p>This is content of the post."</p></body></html>;
}

 

顯然,這樣作的問題在於——一個複雜的頁面HTML代碼每每也很是複雜,而且嵌入在Java代碼中十分不利於維護。

更好的作法是將頁面的HTML代碼寫在模板文件中,而後讀取該文件並返回。Spring自然支持這種很是常見的場景,須要先在pom.xml引入Thymeleaf依賴(接下來的學習中會重點講到):

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

 

將HTML文本保存在src/main/resources/templates/post.html下:

<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <h1>This is title</h1>
    <p> This is Content</h2>
  </body>
</html

 

Controller中能夠去掉@ResponseBody註解,並將URL處理函數的返回值設爲剛剛保存在templates/文件夾中的文件名(不須要擴展名):

@RequestMapping("/posts/{id}")
public String post(@PathVariable("id") int id) {
    return "post";
}

 

Spring框架在發現返回值是"post"後,就會去src/main/resources/templates/目錄下讀取post.html文件並將它的內容返回給瀏覽器。

相關文章
相關標籤/搜索