深入解读Spring Framework Web MVC(第三弹:使用@Controller定义控制器)

先来看一段示例:

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
}

@Controller和@RequestMapping可以让我们能灵活的配置方法签名。在上述例子中,helloWorld方法接受一个Model参数,并返回一个视图名称,当然也可以添加方法其他入参和返回其他类型的值。@Controller、@RequestMapping和其他一些功能注解组成了Spring MVC实现的基础。

@Controller表明了被注解类的服务角色,那就是控制器。Spring不需要去继承任何Controller的基类或引用任何Servlet API。dispatcher会扫描这些被@Controller标记的类并检测@RequestMapping标记的方法。
要开启注解控制器的扫描功能,需要在配置里添加组件扫描。如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 这里的base-package就是我们要进行自动扫描的包路径 -->
    <context:component-scan base-package="com.demo.controller"/>

    <!-- ... -->

</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值