RESTFul与RESTFul案例

RESTFul与RESTFul案例,第1张

RESTFul与RESTFul案例

文章目录
        • 1. 新建maven项目rest
        • 2. 修改pom.xml
        • 3. 新增web模块,修改web.xml
        • 4. 新增SpringMVC配置文件
        • 5. 创建控制器
        • 6. 创建视图文件
        • 7. 在本地tomcat中运行应用
        • 8. 使用HiddenHttpMethodFilter发送put和delete请求

REST(Representational State Transfer,表述性状态转移),是一种架构风格,它提倡URL地址使用统一的风格:从前到后各个单词用斜杠分开,不使用 ?键值对 方式携带请求参数,而是将发送给服务器的参数作为URL地址的一部分,以保证整体风格的一致性。

HTTP协议中有4个常用的 *** 作资源的方式,

  • GET,用于获取资源(查询)。
  • POST,用于新增资源(新增)。
  • PUT,用于更新资源(更改)。
  • DELETE,用于删除资源(删除)。

下面来比较下传统风格与REST风格下,上述四种 *** 作方式的不同。

*** 作方式传统风格REST风格查询(GET请求)getUserById?id=1user/1新增(POST请求)saveUseruser更改(PUT请求)updateUseruser删除 (DELETE请求)deleteUser?id=1user/1 1. 新建maven项目rest 2. 修改pom.xml

修改pom配置文件 ,并添加依赖。pom.xml内容如下,



    4.0.0

    org.example
    rest
    1.0-SNAPSHOT
    war

    
        8
        8
    

    
        
            org.springframework
            spring-webmvc
            5.3.12
        
        
            ch.qos.logback
            logback-classic
            1.3.0-alpha10
        
        
            javax.servlet
            javax.servlet-api
            4.0.1
            provided
        
        
            org.thymeleaf
            thymeleaf-spring5
            3.0.12.RELEASE
        
        
            org.projectlombok
            lombok
            1.18.22
            provided
        
    

3. 新增web模块,修改web.xml

web.xml的配置内容如下,主要配置了编码过滤器CharacterEncodingFilter和前端控制器DispatcherServlet。



    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springMVC.xml
        
    
    
        DispatcherServlet
        /
    

4. 新增SpringMVC配置文件

在resources目录下新建配置文件springMVC.xml,配置内容如下所示,主要配置了组件扫描component-scan和thymeleaf视图解析器ThymeleafViewResolver。




    
    
        
        
        
            
                
                    
                        
                        
                        
                        
                        
                        
                    
                
            
        
    

5. 创建控制器

在java目录下新建Package:com.example.rest.controller,并在该Package下新建类RestController,如下所示,

package com.example.rest.controller;

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;

@Controller
public class RestController {
    @RequestMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getAllUser(){
        System.out.println("查询所有用户信息");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String getUserById(@PathVariable("id") Integer id){
        System.out.println("根据id查询用户信息,id="+id);
        return "success";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String insertUser(String username,String password){
        System.out.println("插入用户,username="+username+" password="+password);
        return "success";
    }

    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String updateUser(String username,String password){
        System.out.println("更新用户,username="+username+" password="+password);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("id") Integer id){
        System.out.println("删除用户,id="+id);
        return "success";
    }
}
6. 创建视图文件

在WEB-INF下新建子目录templates,在templates下新建视图文件:index.html和success.html。




    
    首页


    查询所有用户信息

根据id查询用户信息






    
    success


成功


7. 在本地tomcat中运行应用




由于浏览器只支持get和post,即使在form表单中设置method为put或delete,最后它们还是被当成get处理。
为了发送put请求和delete请求,Spring提供HiddenHttpMethodFilter。

8. 使用HiddenHttpMethodFilter发送put和delete请求

首先,在web.xml中添加HiddenHttpMethodFilter过滤器。



    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

    
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        HiddenHttpMethodFilter
        /*
    

    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springMVC.xml
        
    
    
        DispatcherServlet
        /
    

注意哈,此时web.xml中有两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter。
过滤器的执行顺序有先有后,谁的fliter-mapping在前,谁就越先执行。

然后,修改index.html。




    
    首页


    查询所有用户信息

根据id查询用户信息



如何使用HiddenHttpMethodFilter来发送put和delete请求?需要做到以下两点:

  1. 当前的请求方式必须为post。
  2. 当前请求必须传输参数_mothod,参数值为put或delete。

HiddenHttpMethodFilter是如何实现转发put或delete请求的?看一下HiddenHttpMethodFilter的源码就能理解。

public class HiddenHttpMethodFilter extends OncePerRequestFilter {
    private static final List ALLOWED_METHODS;
    public static final String DEFAULT_METHOD_PARAM = "_method";
    private String methodParam = "_method";

    public HiddenHttpMethodFilter() {
    }

    public void setMethodParam(String methodParam) {
        Assert.hasText(methodParam, "'methodParam' must not be empty");
        this.methodParam = methodParam;
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest requestToUse = request;
        if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
            String paramValue = request.getParameter(this.methodParam);
            if (StringUtils.hasLength(paramValue)) {
                String method = paramValue.toUpperCase(Locale.ENGLISH);
                if (ALLOWED_METHODS.contains(method)) {
                    requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
                }
            }
        }

        filterChain.doFilter((ServletRequest)requestToUse, response);
    }

    static {
        ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    }

    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

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

        public String getMethod() {
            return this.method;
        }
    }
}

着重看下doFilterInternal这个方法,

  1. "POST".equals(request.getMethod()),当前请求方法必须是post。
  2. private String methodParam = "_method";
    String paramValue = request.getParameter(this.methodParam);
    即String paramValue = request.getParameter("_method");,当前请求方法必须包含参数_method。
  3. ALLOWED_METHODS.contains(method)
    ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));,故HiddenHttpMethodFilter可以转发put、delete和patch请求。

最后,重启应用。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5597257.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存