我是靠谱客的博主 粗暴荔枝,最近开发中收集的这篇文章主要介绍深入解读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>

最后

以上就是粗暴荔枝为你收集整理的深入解读Spring Framework Web MVC(第三弹:使用@Controller定义控制器)的全部内容,希望文章能够帮你解决深入解读Spring Framework Web MVC(第三弹:使用@Controller定义控制器)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部