实现接口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注解类型用于声明Spring类的实例是一个控制器(@Controller:web层 @Service:service层 @Repository:dao层);
Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
<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";
}