控制器Controller
- 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
- 控制器负责解析用户的请求并将其转换为一个模型。
- 在Spring MVC中一个控制器类可以包含多个方法
- 在Spring MVC中,对于Controller的配置方式有很多种。
实现Controller接口
Controller是一个接口,该接口下只有一个方法。
| |
| public interface Controller { |
| |
| ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception; |
| } |
测试
- 新建一个子项目
- 编写一个Controller类,ControllerTest1
| |
| |
| public class ControllerTest1 implements Controller { |
| |
| public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { |
| |
| ModelAndView mv = new ModelAndView(); |
| mv.addObject("msg","Test1Controller"); |
| mv.setViewName("test"); |
| return mv; |
| } |
| } |
- 在Spring配置文件中注册bean
| <bean name="/t1" class="com.kuang.controller.ControllerTest1"/> |
- 在WEB-INF/jsp目录下编写,test.jsp
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>P-P</title> |
| </head> |
| <body> |
| ${msg} |
| </body> |
| </html> |
使用注解@Controller
- @Controller注解类型用于声明Spring类的实例是一个控制器
- Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,这需要在配置文件中声明组建扫描。
| <context:component-scan base-package="com.pp.controller"/> |
- 创建一个ControllerTest2,使用注解实现
| package com.pp.controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.ui.Model; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| |
| @Controller |
| |
| public class HelloController { |
| |
| @RequestMapping("/h1") |
| public String hello(Model model){ |
| model.addAttribute("msg","HelloSpringMVCAnnotation"); |
| return "hello"; |
| } |
| |
| |
| @RequestMapping("/h2") |
| public String hello2(Model model){ |
| model.addAttribute("msg","HelloSpringMVCAnnotation22222222222"); |
| return "hello"; |
| } |
| } |
| |
RestFul风格
RestFul就是一个资源定位及资源操作的风格。
功能:
资源:互联网所有的食物都可以被抽象为资源
资源操作:使用post、delete、put、get,使用不同方法对资源进行操作。分别对应 添加、删除、修改、查询。
学习测试:
- 新建一个RestFulController
- 在SpringMVC中可以使用@PathVariable注解,让方法参数的值对应绑定到一个URL模版变量上。
| @Controller |
| public class RestFulController { |
| |
| |
| @RequestMapping("/commit/{p1}/{p2}") |
| public String index(@PathVariable int p1, @PathVariable int p2, Model model){ |
| |
| int result = p1+p2; |
| |
| model.addAttribute("msg", "结果:"+result); |
| |
| return "test"; |
| |
| } |
| |
| } |
方法级别的注解:
| @GetMapping |
| @PostMapping |
| @PutMapping |
| @DeleteMapping |
| @PatchMapping |
其中@GetMapping是使用最多的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南