首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails ActionController 核心服務全解析:URL 映射、Session、過濾器、快取

     編輯:Java 相關知識

在 MVC 架構中,Controller 處理應用邏輯與資料存取。Rails 的 ActionController 提供四大核心服務:URL 映射、Session 追蹤、過濾與驗證、頁面快取。本文詳細解析各服務運作原理與實作範例。

請求處理流程

輸入 https://localhost:3000/demo/say/hello 後:

  1. 載入 app/controllers/say_controller.rb(僅首次)
  2. 實例化 SayController
  3. 載入 app/helpers/say_helper.rb(若存在),混入 Helper 方法
  4. 載入 app/models/say.rb(若存在)

1. URL 映射(Routing)

設定於 config/routes.rb:

ActionController::Routing::Routes.draw do |map|
  map.connect ':controller/service.wsdl', :action => 'wsdl'
  map.connect ':controller/:action/:id'  # 預設路由
end

URL 分為三段::controller/:action/:id。/demo/admin/show/1 映射為:

:controller => 'admin', :action => 'show', :id => 1

Rails 自動呼叫 AdminController#show(1)。

2. Session 追蹤:零樣板碼

Rails 透過 cookies[] 與 session[] 類陣列介面,無需顯式建立物件:

class CookiesController < ApplicationController
  def create_cookie
    cookies[:the_time] = Time.now.to_s
    redirect_to :action => "action_two"
  end
  def get_cookie
    render :text => " #{cookies[:the_time]}"
  end
end

class SessionController < ApplicationController
  def login
    user = User.find_by_name_and_password(params[:user], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to :action => "index"
    else
      reset_session
      flash[:note] = "帳號或密碼錯誤!"
    end
  end
end

flash 為一次性 Session 資料,重導向後自動清除,適合提示訊息。

3. 過濾器與驗證

Before/After Filter

def authorize
  unless session[:user_id]
    flash[:notice] = "請登入"
    redirect_to :controller => "login", :action => "login"
  end
end

class AdminController < ApplicationController
  before_filter :authorize  # 所有 Action 前執行
  # after_filter :log_access  # 所有 Action 後執行
end

Verify:更強大的聲明式驗證

class BlogController < ApplicationController
  verify :only => :post_comment,
         :session => :user_id,
         :add_flash => { :note => "請先登入才能留言" },
         :redirect_to => :index
end

僅針對 post_comment Action,檢查 Session 有 user_id,否則導向首頁並顯示訊息。

4. 頁面快取

針對高頻、低變動頁面,使用 caches_page:

class ContentController < ApplicationController
  before_filter :verify_premium_user, :except => :public_content
  caches_page :public_content  # 產生靜態 HTML 至 public/ 目錄
end

快取層次:caches_page(整頁靜態化)、caches_action(Action 層級)、cache(片段快取)。

進階:RESTful 路由(Rails 2.0+)

map.resources :posts  # 自動生成 7 條 RESTful 路由
# GET    /posts          -> index
# GET    /posts/new      -> new
# POST   /posts          -> create
# GET    /posts/:id      -> show
# GET    /posts/:id/edit -> edit
# PUT    /posts/:id      -> update
# DELETE /posts/:id      -> destroy

總結

ActionController 將 Web 應用的通用關注點(路由、Session、認證授權、快取)封裝為聲明式 API,讓開發者專注於業務邏輯。掌握 before_filter、verify、caches_page 三大工具,即可處理 80% 的 Controller 層需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved