天天看點

[@Controller]1 基于@注釋的控制器配置

[@Controller]1 基于@注釋的控制器配置

标簽: 

基于注釋的控制器配置需要Java 5以上的版本支援。這種注釋支援servlet MVC和Portlet MVC。通過這種方式實作的控制器不需要繼承特定的基礎類,或實作特定的接口。

A、Dispatcher配置檔案

DispatcherServlet和DispatcherPortlet都預設支援注釋配置控制器。以DispatcherServlet為例,它預設支援實作HandlerMapping接口的DefaultAnnotationHandlerMapping和實作HandlerAdapter接口的AnnotationMethodHandlerAdapter來支援注釋配置控制器。所有我們無需在Dispatcher配置檔案中進行顯示配置,就可以支援注釋配置控制器。當然我們也可以自定義HandlerMapping和HandlerAdapter來支援。

下面是顯示定義的例子:

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

</beans>

A.1、自動探測注釋控制器

在原來的方式中Controller是被顯示定義在Dispatcher配置檔案中的一個bean。并且這個Controller執行個體顯示實作Controller接口。在注釋配置控制器時,這個Controller不再擴充控制器基類或應用Servlet API。注釋控制器可以作為一個bean顯示的定義在Dispatcher配置檔案中,也可以不顯示定義讓Dispatcher自動探測。

要實作注釋控制器自動探測,需要在配置檔案中加入探測元件。

自動探測注釋控制器的例子

<?xml version="1.0" encoding="UTF-8"?>

    xmlns:p="http://www.springframework.org/schema/p"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="

    http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="org.xxx" />

    <!—将自動探測org.xxx包中有控制器注釋的類-->

B、基于注釋的Controller

基于注釋的@Controller它不需要在類中顯式的實作Controller,但是它需要Spring 2.5+和Java 5+的支援。

範例1:

Controllers provide access to the application behavior that you typically define through a service

interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

一個最簡單的範例,什麼是控制器,控制器它提供了通路程式的行為,我們通常用一個Servlet來實作。控制器它解釋使用者輸入,并把使用者輸入轉換為一個模型,并通過一個視圖顯示這個模型。

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class HelloWorldController {

    @RequestMapping("/helloWorld")

    public String helloWorld(Model model) {

       model.addAttribute("message", "Hello World!");

       return "helloWorld";

    }

}

@Controller表示HelloWorldController這個類是一個控制器。我們發現這個類并沒有像原來那樣繼承一些Controller的基類或直接實作Controller接口。@RequestMapping("/helloWorld")表示把/helloWorld請求映射到這個類的helloWorld方法上。這個方法接受一個模型Model,并傳回一個String類型的視圖名,後續可以根據這個視圖名,以特定的視圖技術顯示,這個視圖可以通路模型Model資料。