[@Controller]1 基于@注释的控制器配置
(2012-06-14 15:20:33)基于注释的控制器配置需要Java 5以上的版本支持。这种注释支持servlet MVC和Portlet MVC。通过这种方式实现的控制器不需要继承特定的基础类,或实现特定的接口。
A、Dispatcher配置文件
DispatcherServlet和DispatcherPortlet都默认支持注释配置控制器。以DispatcherServlet为例,它默认支持实现HandlerMapping接口的DefaultAnnotationHandler
下面是显示定义的例子:
<beans xmlns="http://www.springframework.org/schema/beans"
<beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandler
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerA
</beans>
A.1、自动探测注释控制器
在原来的方式中Controller是被显示定义在Dispatcher配置文件中的一个bean。并且这个Controller实例显示实现Controller接口。在注释配置控制器时,这个Controller不再扩展控制器基类或应用Servlet API。注释控制器可以作为一个bean显示的定义在Dispatcher配置文件中,也可以不显示定义让Dispatcher自动探测。
要实现注释控制器自动探测,需要在配置文件中加入探测组件。
自动探测注释控制器的例子
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
</beans>
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 {
}
@Controller表示HelloWorldController这个类是一个控制器。我们发现这个类并没有像原来那样继承一些Controller的基类或直接实现Controller接口。@RequestMapping("/helloWorld")表示把/helloWorld请求映射到这个类的helloWorld方法上。这个方法接受一个模型Model,并返回一个String类型的视图名,后续可以根据这个视图名,以特定的视图技术显示,这个视图可以访问模型Model数据。
本文详细介绍了基于注释的Spring MVC控制器配置,包括DispatcherServlet和DispatcherPortlet的配置方式,自动探测注释控制器的方法,以及如何使用@Controller注解创建控制器类。文章深入浅出地解释了控制器的工作原理,提供了示例代码帮助理解。

1671

被折叠的 条评论
为什么被折叠?



