【springboot 入門篇】第3篇 從controller開(kāi)始學(xué)起

雖然文章標(biāo)題是“學(xué)起”,但是我也不會(huì)真的從頭開(kāi)始講,默認(rèn),你是懂springmvc的 o.o

1. 返回?cái)?shù)據(jù)與返回頁(yè)面

在寫web項(xiàng)目的時(shí)候,controller里的返回值一般分為兩種,一種是返回頁(yè)面,也就是ModeAndView,另一種是直接返回?cái)?shù)據(jù),比如json格式的數(shù)據(jù)。

返回一個(gè)頁(yè)面,我們需要用到一些模板引擎,比如熟知的jsp,模板引擎后面會(huì)詳細(xì)講解。

返回?cái)?shù)據(jù)一般會(huì)選擇返回json數(shù)據(jù),我們之前的demo項(xiàng)目中使用的@RestController就是一個(gè)返回?cái)?shù)據(jù)的注解。

@RestController是一個(gè)組合注解,是由@Controller和@ResponseBody組合而成的。
@Controller:將返回值渲染為頁(yè)面。
@ResponseBody:將返回值渲染為數(shù)據(jù)。

2. spring boot支持的模板引擎

spring-boot 支持多種模版引擎包括:

  • FreeMarker
  • Groovy
  • Thymeleaf (Spring 官網(wǎng)使用這個(gè))
  • Velocity
  • JSP (不推薦,jsp在內(nèi)嵌的servlet容器中運(yùn)行有一些問(wèn)題。)

我們?cè)谥v前后端分離之前,都會(huì)使用Thymeleaf模板引擎,先簡(jiǎn)單的介紹一下它。

2.1 Thymeleaf模板引擎

Thymeleaf是一個(gè)java類庫(kù),它是一個(gè)xml/xhtml/html5的模板引擎,可以作為mvc的web應(yīng)用的view層。

Thymeleaf還提供了額外的木塊與spring mvc集成,所以使用ssm框架的也可以使用這個(gè)模板引擎。

本來(lái)想列一下Thymeleaf的用法的,但是感覺(jué)有點(diǎn)多,以后哪里用到哪里講好了。

3. 實(shí)戰(zhàn)

接下來(lái),我們通過(guò)一個(gè)項(xiàng)目,來(lái)實(shí)踐一下兩種不同的返回結(jié)果。

先看一下最終的目錄結(jié)構(gòu):

目錄結(jié)構(gòu)

3.1 創(chuàng)建項(xiàng)目project_1

  • 選擇依賴:web Thymeleaf
選擇依賴

3.2 新建一個(gè)person類,用來(lái)封裝數(shù)據(jù)

package com.example.model;

public class Person {

    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }
}

3.3 新建一個(gè)ViewController,用來(lái)返回一個(gè)視圖

package com.example.controller;

import com.example.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ViewController {

    @RequestMapping("/view")
    public String view(Model model){
        Person person = new Person("x", 22);

        List<Person> list = new ArrayList<>();
        list.add(new Person("a", 11));
        list.add(new Person("b", 12));
        list.add(new Person("c", 13));

        model.addAttribute("onePerson", person);
        model.addAttribute("manyPerson", list);

        return "index";

    }
}

3.4 創(chuàng)建index.html,用來(lái)接收數(shù)據(jù)

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>test</title>

    <link  rel="stylesheet"/>
    <link  rel="stylesheet"/>
</head>

<body>
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">訪問(wèn)model</h3>
        </div>
        <div class="panel-body">
            <span th:text="${onePerson.name}"></span>
        </div>
    </div>

    <div th:if="${not #lists.isEmpty(manyPerson)}">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">列表</h3>
            </div>
            <div class="panel-body">
                <ul class="list-group">
                    <li class="list-group-item" th:each="person:${manyPerson}">
                        <span th:text="${person.name}"></span>
                        <span th:text="${person.age}"></span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</body>
</html>

這里我們使用了Thymeleaf模板引擎來(lái)獲得后臺(tái)傳來(lái)的數(shù)據(jù)并解析,使用bootstrap框架顯示數(shù)據(jù)。可以看到,Thymeleaf的用法和jsp還是有點(diǎn)像的??梢灾苯油ㄟ^(guò)${}的形式來(lái)獲得attribute中的數(shù)據(jù)。

在 spring boot 中,模板引擎默認(rèn)是開(kāi)啟緩存的,如果修改了頁(yè)面內(nèi)容,刷新頁(yè)面是得不到修改后的內(nèi)容的。我們可以在application.yml中關(guān)閉模板引擎緩存:

spring:
  thymeleaf:
    cache: false

如果需要詳細(xì)的Thymeleaf模板的使用方式教程,可以給我留言,我看情況來(lái)決定是否要寫一篇。因?yàn)槲矣玫囊膊皇呛芏?,大部分情況我都是前后端分離的。

3.5 運(yùn)行項(xiàng)目,瀏覽器訪問(wèn)http://localhost:8080/view

view

可以看到,我們成功的在前端獲取到了數(shù)據(jù)。方式就是將數(shù)據(jù)保存在attribute中,然后再前端頁(yè)面獲取。

3.6 修改ViewController中的@Controller為@RestController,重新運(yùn)行

view

我們修改了注解,發(fā)現(xiàn)結(jié)果變了,直接顯示了“index”,是因?yàn)锧RestController會(huì)直接返回?cái)?shù)據(jù),而不是渲染頁(yè)面,所以直接返回了index(這個(gè)index,是return語(yǔ)句中的)

3.7 創(chuàng)建DataController,用來(lái)直接返回?cái)?shù)據(jù)

package com.example.controller;

import com.example.model.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController  // 使用RestController注解
public class DataController {

    @RequestMapping("/person")
    public Person person(){
        return new Person("aa", 10);
    }

    @RequestMapping("persons")
    public List<Person> persons(){
        return Arrays.asList(new Person("bb", 11), new Person("cc", 12));
    }
}

3.8 重新運(yùn)行項(xiàng)目

訪問(wèn)http://localhost:8080/person

person

獲得了json格式的數(shù)據(jù)

訪問(wèn)http://localhost:8080/persons

persons

列表也可以直接渲染為json。

這里需要注意,如果我們方法的返回值是String(參考上面的index),那么返回的結(jié)果就是你return的字符串,如果方法的返回值是一個(gè)對(duì)象(person)或者一個(gè)集合(list,map等),那么得到的結(jié)果就是一個(gè)json字符串。spring boot默認(rèn)使用jackson來(lái)進(jìn)行解析。

jackson也是可以修改為gson或者fastjson的,我們下篇再講。

3.9 修改DataController中的@RestController為@Controller,重新運(yùn)行

訪問(wèn)http://localhost:8080/person

person

訪問(wèn)http://localhost:8080/persons

persons

會(huì)發(fā)現(xiàn)這兩個(gè)都報(bào)錯(cuò)了,因?yàn)锧Controller注解是渲染視圖的,而我們返回的是對(duì)象或者集合,不能完成正常的渲染。

4. 小結(jié)

本文主要講解了spring boot 如何渲染視圖和數(shù)據(jù),講解了@Controller和@RestController的區(qū)別與用法。如果有什么疑問(wèn),請(qǐng)及時(shí)聯(lián)系我。


我之前寫過(guò)一個(gè)重新認(rèn)識(shí)java系類(還沒(méi)寫完,會(huì)寫完的。。),篇幅很長(zhǎng),每一篇文章多的有7、8千字,和多人抱怨說(shuō)看到一半就不想看了,因?yàn)樘L(zhǎng)了,所以 spring boot 這個(gè)系類會(huì)盡量的短小精悍,每篇文章只講一個(gè)知識(shí)點(diǎn),這樣看著不累~

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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