SpringMVC應用和RESTful應用的區別

SpringMVC應用的控制器需要依賴表現層(view)技術,在服務端把數據渲染成html後返回給瀏覽器,而RESTful應用的控制器直接返回一個對象,這個對象會被spring轉成json格式寫到http響應中。
以下是一個簡單的RESTful控制器:

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

可以看到該控制器直接return一個對象。

RESTful應用一般用在前後端分離的項目,RESTful應用返回的json數據可以被前端項目(如nodejs)渲染成html後再返回給瀏覽器。SpringMVC一般用在前後端不分離的項目,因爲View層已經完成了HTML的渲染。

參考文獻:https://spring.io/guides/gs/rest-service/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章