1.控制器Controller
1.1 什么是控制器
- 负责提供解析用户的请求并将其转换成一个模型。
- 在MVC中一个控制器可以提供多种方法。
1.2 Controller注解
- @Controller注解用来声明一个类的实例是一个控制器
- Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
- 编写一个Controller类,使用注解实现
//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2{
//映射访问路径
@RequestMapping("/t2")
public String index(Model model){
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "ControllerTest2");
//返回视图位置
return "test";
}
}
1.3RequestMapping注解
- @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。
- 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
- 使用在方法上面:访问路径:http://localhost:8080 / 项目名 / h1
@Controller
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
- 同时注解类与方法:访问路径:http://localhost:8080 / 项目名/ admin /h1
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
2. RestFul
2.1 什么是RestFul
- RestFul是一种资源定位和资源操作的分格。
- 它不是标准也不是约束,只是一种分格。
- 基于这种分格的程序更简洁,更有层次,更利于实现缓存等。
2.2 功能
资源:互联网所有事物都可以被抽象为资源
资源操作:使用POST,DELETE,PUT,GET方法来对资源进行操作。
分别对应:增删改查
2.3 测试
- 新建一个类Hello
@Controller
public class Hello {
}
- 在Spring MVC中可以使用 @PathVariable 注解,让方法参数的值对应绑定到一个URI模板变量上。
//@Controller自动装配
@Controller
public class Hello {
//url访问域名
@RequestMapping("/hello/{p1}/{p2}")
public String hello(@PathVariable int p1,@PathVariable int p2, Model model)
{
int result = p1+p2;
model.addAttribute("msg","1+2="+result);
return "jsp";
}
}
- 测试
2.4思考
- 如果对应的参数类型不同能不能成功呢?
1.我们来修改下对应的参数类型,再次测试
2.我们在来修改下对应的参数类型,再次测试
public class Hello {
//url访问域名
@RequestMapping("/hello/{p1}/{p2}")
public String hello(@PathVariable int p1,@PathVariable String p2, Model model)
{
String result = p1+p2;
model.addAttribute("msg","result="+result);
return "jsp";
}
}
3 小结
- Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。
- 所有的地址栏请求默认都会是 HTTP GET 类型的。
- 方法级别的注解变体有如下几个:通常可以组合使用
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping