來架個網站吧-17.網站開發-7-MVC-4-Controller

2024-02-28 來架個網站吧 linux 2023 iThome 鐵人賽 Grails

來架個網站吧-17.網站開發-7-MVC-4-Controller

tags: 來架個網站吧 Grails

我是目錄


今天讓我們回到第14天一開始建立的 Controller 。

Grails Controller 是一般API會直接觸及的程式,在這邊主要是處理業務流程。Controller 中有兩項比較常被用到: renderredirect

  • render

render 是表明要回傳的資料。資料可以是TEXTJSONviewtemplates等形式。在程式中的寫會是如下:

class ExampleController {

    def dictService

    def index(){
      render(view: "example")
    }

    /**
     * 查詢
     * @return
     */
    JSON filter(){
        LinkedHashMap result = dictService.filter(params)

        render result as JSON
    }
}
  • redirect

redirect 顧名思義是跳轉的概念。會在 Web Server 中使用 HTTP 通訊協定重新導向到新增目的地。在程式中的寫會是如下:

class ExampleController {

    def index(){
      redirect controller: 'dict', action: 'index' ,id: 'test'
    }

    def goToGoogle(){

        redirect(url: "http://www.google.com")
    }
}

在這邊有草過一個坑: 在 redirect 中參數 id 傳遞中文需要進行 URL encode,不然出現下列類似錯誤

tomcat The Unicode character [主] at code point [20,027] cannot be encoded as it is outside the permitted range of 0 to 255。

出現這個問題,主要是在RFP822 3.1.2章節中 HTTP 表頭規範需要在 0到 255 的ASCII代碼範圍中,且不包含小數點及冒號。

今天的程式進度如下:

package dict

import grails.converters.JSON

class DictController {

    def dictService

    def index() { }

    /**
     * 查詢
     * @return
     */
    JSON filter(){
        LinkedHashMap result = dictService.filter(params)

        render result as JSON
    }
}

參考資料

render

redirect

API 設計時必須注意的 HTTP header 底線問題

RFP822 3.1.2: STRUCTURE OF HEADER FIELDS