1.@Controller
相信大家写web项目时Controller层是我们经常接触的,那我们老方法定义一个Controller类需要继承父类、继承方法、重写方法内容等等,下面先给出老方法Controller层的定义方法:
public class TestController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
//业务代码
String name = "HelloSpringMVC!";
modelAndView.addObject("name",name);
//视图跳转:跳转至xml中配置的视图解析器,拼接名字,跳转视图。
modelAndView.setViewName("test");
return modelAndView;
}
}
下面给出使用@Controller注解的定义方法:
@Controller
public class MyController {
@GetMapping ("/hello")
public String hello(Model model){
model.addAttribute("msg","HelloMVC annotation!");
return "hello";
}
}
代码一下变得简洁起来,我们Spring MVC 提供了一个基于注解的编程模型,其中@Controller
组件@RestController使用注解来表达请求映射、请求输入、异常处理等。带注释的控制器具有灵活的方法签名,不必扩展基类,也不必实现特定的接口。
并且我们如果想要定义多个Controller接口的话,不需要像老方法去在新建一个类,只需要新定义一个方法便好。
我们点进@Controller的源码第一层便发现有我们Spring常见的@Component注解,这说明构造@Controller型允许自动检测,与 Spring 对检测@Component类路径中的类并为它们自动注册 bean 定义的一般支持保持一致。它还充当带注解类的原型,表明其作为 Web 组件的角色。
2.@RquestMapping及其变体
我们可以使用@RquestMapping注释将请求映射到控制器方法。它有各种属性来匹配 URL、HTTP 方法、请求参数、标头和媒体类型。您可以在类级别使用它来表达共享映射,或者在方法级别使用它来缩小到特定的端点映射。例如:
@Controller
public class MyController {
@RequestMapping ("/hello")
public String hello(Model model){
model.addAttribute("msg","HelloMVC annotation!");
return "hello";
}
}
使用tomcat服务器启动之后,浏览器请求”localhost:8080/hello"便会进入上方的hello方法。
@RquestMapping还有 HTTP 方法特定的快捷方式变体@RequestMapping
:
-
@GetMapping
-
@PostMapping
-
@PutMapping
-
@DeleteMapping
-
@PatchMapping
这些注解只有在请求方式对应下的情况下才会生效。
快捷方式是提供的自定义注解,因为可以说,大多数控制器方法应该映射到特定的 HTTP 方法,而不是 使用@RequestMapping
,默认情况下,它匹配所有 HTTP 方法。@RequestMapping
在类级别仍然需要在整体类上使用来表示共享映射。
3.RestFul风格
我们之前使用的部分url带参数的方式可能部分如下:
一个问号后衔接参数,如若参数过多,则需要大量连接符参与,不美观简洁也不方便。
不用RestFul风格:
//http://localhost:8080/t2?a=1&b=2
@RequestMapping("/t2")
public String test1(Model model,int a, int b){
int res = a + b;
model.addAttribute("msg","结果为" + res);
return "hello";
}
使用RestFul风格 在参数前加入@PathVariable注解:
//RestFul风格:http://localhost:8080/t2/1/2
@GetMapping("/t2/{a}/{b}")
public String test1(Model model,@PathVariable int a,@PathVariable int b){
int res = a + b;
model.addAttribute("msg","结果为" + res);
return "test";
}
4.使用RestFul风格相同URL不同请求
相同的url不同请求:url = "http://localhost:8080/t2/1/2"
1.get请求
@GetMapping("/t2/{a}/{b}")
public String test1(Model model,@PathVariable int a,@PathVariable int b){
int res = a + b;
model.addAttribute("msg","结果为" + res);
return "test";
}
2.post请求
@PostMapping("/t2/{a}/{b}")
public String test2(Model model,@PathVariable int a, @PathVariable int b){
int res = a - b;
model.addAttribute("msg","结果为" + res);
return "test";
}
使用RestFul风格URI 变量会自动转换为适当的类型,或者TypeMismatchException
异常被引发。默认支持简单类型(int,long,Date等),也可以注册对任何其他数据类型的支持。
推荐显式命名 URI 变量(例如@PathVariable("customId")
),采用显示命名的方式,url中{}中也必须是你显示命名的名称。这样可以清晰的分辨前端传来的变量。