4 控制器Controller和RestFul
我们来看一下SpringMVC中控制器和路径请求的具体内容吧!
4.1 控制器Controller
控制器Controller
- 控制器复杂提供访问应用程序的行为,通常通过定义接口或者注解定义两种方式实现。
- 控制器负责解析用户的请求并将其转换为一个模型。
- 在SpringMVC中一个控制器类可以包含多个方法
- 在SpringMVC中,对于Controller的配置方法有多种
4.1.1 实现Controller接口
Controller是一个接口,在 org.springframework.web.servlet.mvc 包下,接口中只有一个方法:
//实现该接口的类获得控制器功能
public interface Controller {
//处理请求并返回一个模型与视图的对象
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
测试
- 新建一个Module,springmvc-04-controller。使用03中的代码,操作一下完成基本架构的创建
- 删除HelloController.java
- springmvc-servlet.xml中只留下 视图解析器!
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
- 编写一个Controller类,ControllerTest1
//定义控制器
//注意不要倒错包,实现Controller接口,重写方法
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//返回一个视图模型对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "这是实现Controller接口控制器!");
mv.setViewName("test");
return mv;
}
}
- 去Spring配置文件中注册请求bean;name对应请求路径,class对应处理请求的类
<bean name="/t1" class="com.serene.controller.ControllerTest1"/>
- 编写前端test.jsp,注意位置/WEB-INF/jsp/test.jsp,对应我们的视图解析器
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ControllerTest</title>
</head>
<body>
${msg}
</body>
</html>
- 配置Tomcat运行测试,注意我们没有项目发配名,配置的就是一个/,所以不用加项目名!
说明:
- 实现接口Controller定义控制器是较老的方法
- 缺点是:一个控制器中只有一个方法,如果需要多个方法则需要定义多个Controller;定义的方式比较麻烦。
4.1.2 使用注解@Controller
- @Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还讲到了另外三个注解);
- Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能够找到你的控制器,需要在配置文件中声明组件扫描。
<context:component-scan base-package="com.serene.controller"/>
- 增加一个ControllerTest2类,使用注解实现控制器
//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2 {
//映射访问路径
@RequestMapping("/t2")
public String annotation(Model model){
//SpringMVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "这是注解实现Controller!");
//返回视图位置
return "test";
}
}
- 运行Tomcat测试
可以发现,两种方式的两个请求都指向一个视图,但是页面返回的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱耦合的关系。
注解方式是平时使用的最多的方式!
RequestMapping
@RequestMapping
- @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或者方法上。用于类上,表示类中的所有相应请求的方法都是以该地址作为父路径。
- 只注解在方法上面,无父路径。项目名在配置Tomcat的时候设置,此处无
//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2 {
//访问路径:http://localhost:8080/项目名/t3
@RequestMapping("/t3")
public String annotation1(Model model){
//SpringMVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "RequestMapping测试:----> t3!");
//返回视图位置
return "test";
}
访问路径:http://localhost:8080/项目名/h2
@RequestMapping("/h2")
public String annotation2(Model model){
//SpringMVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "RequestMapping测试:----> -h2!");
//返回视图位置
return "test";
}
}
- 同时注解类与方法,访问地址需要加上父路径。先指定类的路径再指定方法的路径。
@Controller
@RequestMapping("/RM")
public class TestController {
//访问路径:http://localhost:8080/项目名/RM/h1
@RequestMapping("/h1")
public String test(Model model){
model.addAttribute("msg", "RequestMapping测试:----> h1!");
return "test";
}
//访问路径:http://localhost:8080/项目名/RM/h2
@RequestMapping("h2")
public String test1(Model model){
model.addAttribute("msg", "RequestMapping测试:----> h2!");
return "test";
}
}
@RequestMapping注释参数中,不需要加/ 也可以访问到?? 是的!
4.2 RestFul风格
概念
RestFul就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更加简洁,更有层次,更易于实现缓存等机制。
功能
资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同的方法对资源进行操作。
分别对应 添加、删除、修改、查询。
传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RestFul操作资源:可以通过不同的请求方式来实现不同的效果!如下面,请求地址一致,但是功能可以不同!
http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE
学习测试
- 新建一个类RestFulController
@Controller
public class RestFulController {
}
- 在SpringMVC中可以使用 @PathVariable 注解,让方法参数的值对应绑定到一个url模板变量上
@Controller
public class RestFulController {
//映射一个访问路径
@RequestMapping("/restful/{p1}/{p2}")
public String testFul(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//SpringMVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:result="+result);
//返回视图位置
return "test";
}
}
- 通过设置访问路劲添加参数。测试
- 思考:使用路劲变量的好处?
- 使路劲变得更加简洁;
- 获得参数更加方便,框架会自动进行类型转换
- 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,如果 3 中访问的路径访问路劲为http://localhost:8080/restful/aaa/5 访问失败,路径与方法不匹配,而不是参数转换失败。
- 修改对应参数类型,再次测试
@Controller
public class RestFulController {
//映射一个访问路径
@RequestMapping("/restful/{p1}/{p2}")
public String testFul(@PathVariable String p1, @PathVariable int p2, Model model){
//int result = p1+p2;
String result = p1+p2;
//SpringMVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:result="+result);
return "test";
}
}
使用method属性指定请求类型
用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET、POST、HEAD、OPTIONS、PUT、PATCH、DELETE、TRACE等
我们测试一下:
- 增加一个方法
//使用method属性指定请求类型
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String test2(Model model){
model.addAttribute("msg", "***method=POST | GET!");
return "test";
}
- 在浏览器地址栏进行访问默认是GET请求,会报错:
- 如果将 RequestMethod.POST 改为 GET 则正常了
小结:
SpringMVC 的 @RequestMapping 注解能够处理 HTTP请求的方法,比如 GET、PUT、POST、DELETE以及PATCH。
所有地址栏请求默认都会是HTTP GET类型的。
方法级别的注解变体有如下几个:组合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping 是一个组合注解,平时使用的会比较多!
它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。
对应代码:springmvc-04-controller