控制器Controller
控制器Controller
- 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
- 控制器负责解析用户的请求并将其转换为一个模型。
- 在Spring MVC中一个控制器类可以包含多个方法
- 在Spring MVC中,对于Controller的配置方式有很多种
实现接口Controller定义控制器是较老的办法:
public class HelloController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//封装对象,放在ModelAndView中。Model
String aa = "HelloSpringMVC!";
mv.addObject("abc",aa);
//mv.addObject("abv","aaaa!");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
return mv;
}
}
缺点:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦;
@Controller注解
@Controller注解类型用于声明Spring类的实例是一个控制器(@Controller:web层 @Service:service层 @Repository:dao层);
Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.zhang.controller"/>
@Controller注解的类会自动添加到Spring上下文中
@RequestMapping 设置映射访问路径
@Controller
public class HelloController {
@RequestMapping("/t2")
public String test2(User user, Model model) {
model.addAttribute("msg", user.toString());
return "hello";
}
}
@RequestMapping 也可以放在类上,这样在每个方法的请求路径前面都要加上类上的路径
@Controller
@RequestMapping("/controller")
public class HelloController {
@RequestMapping("/t2")
public String test2(User user, Model model) {
model.addAttribute("msg", user.toString());
return "hello";
}
}
请求类型
用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等。
POST请求:
@RequestMapping(value = "/hello", method = {RequestMethod.POST})
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}
使用浏览器地址栏进行访问默认是Get请求,会报错405:
改为Get请求
@RequestMapping(value = "/hello", method = {RequestMethod.GET})
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}
可以正常访问:
组合注解:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping("/hello")
相当于
@RequestMapping(value = "/hello", method = {RequestMethod.GET})
// @RequestMapping(value = "/hello", method = {RequestMethod.GET})
@GetMapping("/hello")
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}