第一章 REST【RESTful】风格CRUD

1.1 REST的CRUD与传统风格CRUD对比
  • 传统风格CRUD

    • 功能 URL 请求方式
    • 增 /insertEmp POST
    • 删 /deleteEmp?empId=1001 GET
    • 改 /updateEmp POST
    • 查 /selectEmp?empId=1001 GET
  • REST风格CRUD

    • 功能 URL 请求方式
    • 增 /emp POST
    • 删 /emp/1001 DELETE
    • 改 /emp PUT
    • 查 /emp/1001 GET
1.2 REST风格CRUD优势
  • 提高网站排名
    • 排名方式
      • 竞价排名
      • 技术排名
  • 便于第三方平台对接
1.3 实现PUT&DELETE提交方式步骤
  • 注册过滤器HiddenHttpMethodFilter
  • 设置表单的提交方式为POST
  • 设置参数:_method=PUT或_method=DELETE
1.4 源码解析HiddenHttpMethodFilter
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 {

   HttpServletRequest requestToUse = request;

   if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
      String paramValue = request.getParameter(this.methodParam);
      if (StringUtils.hasLength(paramValue)) {
         String method = paramValue.toUpperCase(Locale.ENGLISH);
         if (ALLOWED_METHODS.contains(method)) {
            requestToUse = new HttpMethodRequestWrapper(request, method);
         }
      }
   }

   filterChain.doFilter(requestToUse, response);
}
/**
	 * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
	 * {@link HttpServletRequest#getMethod()}.
	 */
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}
12-24 12:47