SpringMVC框架|REST开发风格


一、REST开发风格

REST即(Representational State Transfer):(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,正得到越来越多网站的采用。

  • 资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URL(统一资源定位符)指向它,每种资源对应一个特定的URI。要获取这个资源,访问它的URi就可以,因此URI即为每一个资源的独一无二的识别符。

  • 表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用txt格式表现出来,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式。

  • 状态转化(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发送"状态转化"(State Transfer)。而这种转化是建立在表现层之上的,所以就是"表现层状态转化"。具体说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。

REST开发风格:以简洁的URL提交请求,以请求方式区分对资源操作。

二、使用@PathVariable获取路径上的占位符

@PathVaariable注解可以映射URL绑定的占位符。

  • 带占位符的URL是Spring3.0新增的功能。该功能在SpringMVC向REST目标挺进发展过程中具有里程碑的意义。
  • 通过@PathVariavle可以将URL中占位符参数绑定到控制器处理方法的参数中:URL中的{xxx}占位符可以通过@PathVariable(“xxx”)绑定到操作方法的参数中。
	// 路径上可以有占位符,可以在任意路径的地方写一个{变量名}
	@RequestMapping("/user/{id}")
	public String hello05(@PathVariable("id") String id) {
		System.out.println("路径上占位符的值:" + id);
		return "success";
	}

在这里插入图片描述
在这里插入图片描述

三、演示restful开发风格

实际上REST开发风格是一种很理想化的开发风格,从页面上只能发起两种请求(GET、POST),如何从页面发起PUT、DELETE请求呢?Spring提供了对Rest风格的支持。

  • SpringMVC中有一个HiddenHttpMethodFilter:它可以把普通的请求转化为规定形式的请求。
  • 创建一个post类型的表单,表单项中携带一个_method的参数,这个_method的值就是DELTER或者PUT。

1.index.jsp

主页面,该页面包含增删改查四个操作;分别使用GET、POST、DELETE、PUT方式发送请求。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- 发起图书的增删改查(REST风格) -->
	<a href="book/1">查询图书</a><br/>
	
	<form action="book" method="post">
		<input type="submit" value="添加图书"/>
	</form>
	
	<form action="book/1" method="post">
		<input name="_method" value="DELETE">
		<input type="submit" value="删除图书"/>
	</form>
	
	<form action="book/1" method="post">
		<input name="_method" value="PUT">
		<input type="submit" value="更新图书"/>
	</form>
</body>
</html>

2.Controller

控制器中使用@PathVariable注解获取路径上的占位符。

@Controller
public class BoolController {
	@RequestMapping(value = "/book/{bid}", method = RequestMethod.GET)
	public String getBook(@PathVariable("bid") Integer id) {
		System.out.println("查询到了" + id + "号图书");
		return "success";
	}

	@RequestMapping(value = "/book/{bid}", method = RequestMethod.DELETE)
	public String deleteBook(@PathVariable("bid") Integer id) {
		System.out.println("删除了" + id + "号图书");
		return "success";
	}

	@RequestMapping(value = "/book/{bid}", method = RequestMethod.PUT)
	public String updateBook(@PathVariable("bid") Integer id) {
		System.out.println("更新了" + id + "号图书");
		return "success";
	}

	@RequestMapping(value = "/book", method = RequestMethod.POST)
	public String addBook() {
		System.out.println("添加了新的图书");
		return "success";
	}
}

3.web.xml

配置前端控制器与HiddenHttpMethodFilter。

  • 前端控制器作为所有请求的中转站。
  • HiddenHttpMethodFilter使Spring支持DELETE和PUT请求。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>2.SpringMVC_rest</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	
	<!-- 前端控制器 -->
	<!-- The front controller of this Spring Web application, responsible for 
		handling all application requests -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

4.springmvc.xml

  • component-scan:扫包。
  • InternalResourceViewResolve:配置视图解析器,可以拼接页面地址。
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
	<context:component-scan base-package="com.gql"></context:component-scan>
	
	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

5.测试

在这里插入图片描述
依次点击增删改查按钮:
在这里插入图片描述
每次都能成功在控制台打印信息,并跳转至Success页面。

四、HiddenHttpMethodFilter源码分析

public class HiddenHttpMethodFilter extends OncePerRequestFilter {
	
	public static final String DEFAULT_METHOD_PARAM = "_method";
	private String methodParam = DEFAULT_METHOD_PARAM;
	
	...
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//获取表单上_method的值
		String paramValue = request.getParameter(this.methodParam);
		//判断如果表单的请求是POST并且_method有值
		if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
			//将_method的值转换为大写
			String method = paramValue.toUpperCase(Locale.ENGLISH);
			//重写了getMethod方法==PUT/delete
			HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
			filterChain.doFilter(wrapper, response);
		}
		//否则直接放行
		else {
			filterChain.doFilter(request, response);
		}
	}
	...
}

五、高版本tomcat不支持DELETE、PUT请求问题

解决方案:在JSP页面头部加上isErrorPage="true"

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hudie.

不要打赏!不要打赏!不要打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值