Spring学习笔记_34——@Controller

1. 介绍

在Spring框架中,@Controller注解是一个非常重要的组件,它用于定义一个类为Spring MVC的控制器(Controller)。这个注解会告诉Spring框架,被标注的类是一个Web控制器,并且可以处理HTTP请求。

2. 特点

  • 组件扫描 :@Controller注解的类会被Spring的组件扫描机制自动检测到,并注册为Spring容器中的一个Bean。这意味着你不需要在XML配置文件中手动声明这个Bean。
  • 请求映射 :通常与@RequestMapping或其变体(如@GetMapping,@PostMapping等)一起使用,以定义哪些URL应该触发控制器中的特定方法。这些注解可以放在类级别或方法级别上,用来指定请求的路径、HTTP方法等。
  • 数据绑定:控制器中的方法可以通过方法参数接收来自客户端的数据,例如表单提交的数据或URL中的参数。Spring MVC会自动将请求参数绑定到方法参数上。
  • 视图解析 :控制器方法通常返回一个逻辑视图名称,Spring会根据这个名称找到相应的视图资源来渲染页面。也可以直接返回视图对象或者使用@ResponseBody直接写出响应内容。

3. 源码

java 复制代码
/**
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 2.5
 * @see Component
 * @see org.springframework.web.bind.annotation.RequestMapping
 * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    // Spring类型的属性,表示注入IOC容器时Bean的唯一标识
	@AliasFor(annotation = Component.class)
	String value() default "";

}
4. Demo
java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

    @GetMapping("/hello")
    public String sayHello(@RequestParam(value = "name", required = false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "hello"; // 返回逻辑视图名,这里假设有一个名为 "hello" 的视图模板
    }
}
java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @GetMapping
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "hello";  // 返回视图名称,通常对应一个模板文件(如 Thymeleaf, JSP 等)
    }
}
相关推荐
会编程的吕洞宾5 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
xurileidian7 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
斑鸠喳喳10 小时前
Spring IoC 之 BeanFactoryPostProcessor
java·spring
不得了zz1 天前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
会编程的吕洞宾1 天前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
CoderYanger2 天前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github
nice_lcj5202 天前
Spring 事务:声明式事务怎么生效
java·spring·面试·事务·transactional·传播机制
vx-程序开发2 天前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业
nice_lcj5202 天前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
nice_lcj5202 天前
Spring Boot 入门:几行配置怎么跑起来
java·spring boot·spring·面试·自动配置·起步依赖