HTTP Status 405 - JSPs only permit GET POST or HEAD问题的分析和解决办法

1.出错时的代码

(1)web.xml



    
        contextConfigLocation
        /WEB-INF/applicationContext.xml
    
​
    
    
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        HiddenHttpMethodFilter
        /*
    
  
    
    
    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
    
    
        dispatcher
        /
    

(2)dispatcher-servlet.xml



​
     
    
    
    
        
        
    

(4)Test.java

    @RequestMapping(value = "order", method = RequestMethod.DELETE)
    @ResponseBody()
    public String testOrderDelete(@RequestParam("id") Integer id) {
        System.out.println("删除id为" + id + "的员工");
        return "success";
    }
​
    @RequestMapping(value = "order", method = RequestMethod.PUT)
    @ResponseBody()
    public String testOrderPut(@RequestParam("id") Integer id) {
        System.out.println("更新id为" + id + "的员工");
        return "success";
    }

(5)index.jsp

  id:        
  id:        

2.错误原因分析

当在index.jsp中提交后,HiddenHttpMethodFilter会将method转换成对应的DELETE或PUT,SpingMVC会继续用对应的请求重定向到success.jsp中,而jsp只支持GET、POST、HEAD请求方法。

3.解决方法

(1)为controller里的方法加上@ResponseBody()注解,并且返回一个字符串。不过此方法无法进入指定success.jsp页面。

  @RequestMapping(value = "order", method = RequestMethod.PUT)
    @ResponseBody()
    public String testOrderPut(@RequestParam("id") Integer id) {
        System.out.println("更新id为" + id + "的员工");
        return "success";
    }

(2)使用重定向跳转到指定页面

  @RequestMapping(value = "order", method = RequestMethod.DELETE)
    public String testOrderDelete(@RequestParam("id") Integer id) {
        System.out.println("删除id为" + id + "的员工");
        //无法重定向到WEB-INF目录中,若要访问,需把该页面放入其它路径
        return "redirect:success.jsp";
    }

(3)taocat换到7.0以及以下版本

(4)在你的success页面头部文件设置其页面为错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%>

4.HiddenHttpMethodFilter转换请求的源码

   private String methodParam = "_method";
​
    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);
    }

 

你可能感兴趣的:(SpringMVC)