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 等)
    }
}
相关推荐
NE_STOP2 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
JavaGuide3 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
玹外之音3 天前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉3 天前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP3 天前
springMVC-常见视图组件与RESTFul编程风格
spring
what丶k4 天前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
NE_STOP4 天前
springMVC-获取前端请求的数据与三个作用域
spring
莫寒清4 天前
Spring MVC:@PathVariable 注解详解
java·spring·mvc
-大头.4 天前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(1)
spring
莫寒清4 天前
Apache Tika
java·人工智能·spring·apache·知识图谱