RestFul和控制器
-
控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
-
控制器负责解析用户的请求并将其转换为一个模型。
-
在Spring MVC中一个控制器类可以包含多个方法
-
在Spring MVC中,对于Controller的配置方式有很多种
1.实现Controller接口
Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法;
//实现该接口的类获得控制器功能
public interface Controller {
//处理请求且返回一个模型与视图对象
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
测试
1.新建一个Moudle,springmvc-04-controller 。
添加web支持 新建lib 添加jar包!
2.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--1.配置DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求;(不包括.jsp)-->
<!--/* 匹配所有的请求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.编写一个Controller类,ControllerTest1
package com.cy.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//定义控制器
//注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
4.添加Spring MVC配置文件
在resource目录下添加springmvc-servlet.xml配置文件,配置的形式与Spring容器配置基本类似,为了支持基于注解的IOC,设置了自动扫描包的功能,具体配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.cy.controller"/>
<!-- 让Spring MVC不处理静态资源 .css .js .html .mp3 .mp4-->
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
5.写要跳转的jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC</title>
</head>
<body>
${msg}
</body>
</html>
6.去Spring配置文件中注册请求的bean;
name对应请求路径,class对应处理请求的类
<bean name="/t1" class="com.cy.controller.ControllerTest1"/>
7.配置Tomcat运行测试,
我这里没有项目发布名配置的就是一个 / ,所以请求不用加项目名,OK!
2.使用注解@Controller
-
@Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还提到了另外3个注解);
-
Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.cy.controller"/>
- 增加一个ControllerTest2类,使用注解实现;
//@Controller注解的类会自动添加到Spring上下文中
@Controller //代表这个类会被spring接管,被这个注解的类,如果返回值是String 并且具体页面可以跳转,那么就会被视图解析器解析
public class ControllerTest2{
//映射访问路径
@RequestMapping("/t2")
public String index(Model model){
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "ControllerTest2");
//返回视图位置
return "test";//WEB-INF/jsp/test.jsp
}
}
- 运行tomcat测试
可以发现,我们的两个请求都可以指向一个视图,但是页面结果的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱偶合关系。
注解方式是平时使用的最多的方式!
3.RequestMapping
@RequestMapping
-
@RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
-
为了测试结论更加准确,我们可以加上一个项目名测试 myweb
-
只注解在方法上面
@Controller
public class ControllerTest3{
@RequestMapping("/h1")
public String test(){
return "test";
}
}
-
访问路径:http://localhost:8080 / 项目名 / h1
-
同时注解类与方法
@Controller
@RequestMapping("/admin")
public class ControllerTest4 {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
访问路径:http://localhost:8080 / 项目名/ admin /h1 , 需要先指定类的路径再指定方法的路径;
RestFul 风格
概念:
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
功能
-
资源:互联网所有的事物都可以被抽象为资源
-
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
-
分别对应 添加、 删除、修改、查询。
传统方式操作资源 :
通过不同的参数来实现不同的效果!方法单一,post 和 get
-
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
学习测试
传统方式写法:
1.在新建一个类 RestFulController
package com.cy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add")
public String test1(int a, int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
测试请求查看下
http://localhost:8080/add?a=1&b=2
RestFul风格写法
2.在Spring MVC中可以使用 @PathVariable 注解,让方法参数的值对应绑定到一个URI模板变量上。
@Controller
public class RestFulController {
@RequestMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
测试请求查看下
http://localhost:8080/add/1/2
思考:使用路径变量的好处?
- 使路径变得更加简洁;
- 安全,防止注入
- 获得参数更加方便,框架会自动进行类型转换。
通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,如这里访问是的路径是/commit/1/a,则路径与方法不匹配,而不会是参数转换失败。
3.我们来修改下对应的参数类型,再次测试
@Controller
public class RestFulController {
//映射访问路径
@RequestMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable String b, Model model){
String res = a+b;
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:"+res );
//返回视图位置
return "test";
}
}
我们在来测试请求查看下
http://localhost:8080/add/1/2
使用method属性指定请求类型
用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等
我们来测试一下:
- 增加一个方法
//映射访问路径,必须是POST请求
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String test2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
另一种写法:
@GetMapping("/hello")
public String test2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
- 我们使用浏览器地址栏进行访问默认是Get请求,会报错405:
如果将POST修改为GET则正常了;
创建一个表单a.jsp
放在WEB-INF目录下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC</title>
</head>
<body>
<form action="/add/1/3" method="post">
<input type="submit">
</form>
</body>
</html>
@Controller
public class RestFulController {
@PostMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
@GetMapping("/add/{a}/{b}")
public String test2(@PathVariable int a, @PathVariable String b, Model model){
String res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
我们来测试一下:
http://localhost:8080/add/1/1
我们可以发现Post请求 正常执行,然后继续测试Get请求
http://localhost:8080/a.jsp
我们可以发现Get请求也执行了,
所以我们可以通过不同的请求方式来实现不同的效果!
小结:
Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。
所有的地址栏请求默认都会是 HTTP GET 类型的。
方法级别的注解变体有如下几个:组合注解
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
@GetMapping 是一个组合注解,平时使用的会比较多!
它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。