SpringMVC 框架使用RESTful 架构获取参数

给大家解答一下Java SpringMvc 框架中RESTful 架构的实现方式。 排版就先这样吧,凑合一下。

再SpringMvc 框架中,RESTful 的请求方式是支持的,但是无法获取传递的参数,需要先实现一个HiddenHttpMethodFilter 拦截器。

老方式的实现我就不再声明了,在servlet 3.0+ 规范中已推荐抛弃web.xml 文件配置web 应用了,所以可以这样实现拦截器。

import javax.servlet.annotation.WebFilter;
 
import org.springframework.web.filter.HiddenHttpMethodFilter;
 
@WebFilter("/*")
public class MethodFilter extends HiddenHttpMethodFilter{
          
   
 
}

有spring 源码的同学进入HiddenHttpMethodFilter 类后可以发现已下代码。

public static final String DEFAULT_METHOD_PARAM = "_method";
@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);
        }

可以发现,实现的方式是通过post 方式提交,在参数中提交一个"_method" 的参数,大小无视,因为会被经过 toUpperCase(Locale.ENGLISH) 处理。

那么实现了拦截器后,让我们回到Controller 中。 方法上加以下注解。

@RequestMapping(method = RequestMethod.PUT)

详细的基础就不再说明,RequestMethod 支持以下枚举参数。

public enum RequestMethod {
          
   
 
        GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
 
}
经验分享 程序员 微信小程序 职场和发展