springmvc中的REST风格详细讲解

一、什么叫REST

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

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

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

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

二、看完上面对REST的解释是不是一脸懵比呢,没关系我们通过代码实例来解读

 实际上REST就是一种新型的CRUD操作方式,那么SpringMVC是怎么实现的呢

1. 默认只支持POST、GET,所以需要在web.xml配置 HiddenHttpMethodFilter来支持PUT、DELETE

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <!-- 请求method支持 put和delete必须添加过滤器 -->
  <filter>
    <filter-name>myFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <!-- SpringMVC的前端控制器 -->
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 设置自己定义的控制器xml文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

HiddenHttpMethodFilter源码:

@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)) {
                requestToUse = new HttpMethodRequestWrapper(request, paramValue);
            }
        }

        filterChain.doFilter(requestToUse, response);
    }

通过源码可以知道SpringMVC可以把post请求转换为delete和put,我们只需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT即可

2.在user.jsp编写REST风格的CRUD请求


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--添加--%>
    <form action="${pageContext.request.contextPath}/user" method="post">
        <input type="text" name="name"/>
        <input type="submit" value="添加"/>
    </form>
    <br/>
    <%--删除--%>
    <form action="${pageContext.request.contextPath}/user/delete" method="post">
        <input  type="hidden" name="_method" value="delete"/>
        <input type="text" name="name"/>
        <input type="submit" value="删除"/>
    </form>
    <br/>
    <%--修改--%>
    <form action="${pageContext.request.contextPath}/user/update" method="post">
        <input  type="hidden" name="_method" value="put"/>
        <input type="text" name="id"/>
        <input type="submit" value="修改"/>
    </form>
</body>
</html>

3.编写控制层

package cn.et.demo1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;

/**


 *  资源(有一个唯一标识符)
 *  对资源的操作就是一动作(GET(查) | POST (新增)| PUT(修改) |DELETE(删除)
 *  rest是一种设计风格 设计资源的标识符
 */
@Controller
public class RestController {

    /**
     * 添加
     * @param name
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user",method=RequestMethod.POST)
    public String addUser(String name,HttpServletResponse response) throws Exception{
        response.getWriter().println(name+" 添加成功!!");
        return null;
    }

    /**
     * 删除
     * @param userId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable(value="id") String userId,HttpServletResponse response) throws Exception{
        response.getWriter().println(userId+" 删除成功!!");
        return null;
    }

    /**
     * 修改
     * @param userId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
    public String updateUser(@PathVariable(value="id") String userId,HttpServletResponse response) throws Exception{
        response.getWriter().println(userId+" 修改成功!!");
        return null;
    }

    /**
     * 查询
     * @param userId
     * @return
     */
    @RequestMapping(value="/user/{id}",method=RequestMethod.GET)
    public String getUser(@PathVariable(value="id") String userId, HttpServletResponse response)throws Exception{
        response.getWriter().println(userId+" 查询成功!!");
        return null;
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值