Resolving HTTP Method Mismatch in SpringMVC: From 405 Errors to Solutions

Nov 25, 2025 · Programming · 10 views · 7.8

Keywords: SpringMVC | HTTP 405 Error | Request Method Mapping

Abstract: This article provides an in-depth analysis of common HTTP 405 errors in SpringMVC framework, focusing on improper configuration of method parameter in @RequestMapping annotation. Through practical code examples, it explains the differences between GET and POST methods and offers multiple solutions. The article also examines SpringMVC's request processing mechanism and DispatcherServlet workflow to help developers fundamentally understand and avoid such errors.

Problem Background and Phenomenon Analysis

HTTP 405 error is a common yet confusing issue in SpringMVC development. When developers encounter error messages like "Request method 'GET' not supported", they need to deeply understand SpringMVC's request mapping mechanism to identify the root cause.

Core Problem Analysis

Let's analyze this issue through a typical code example:

@Controller
public class HelloWordController {
    private Logger logger = LoggerFactory.getLogger(HelloWordController.class);

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String welcome() {
        logger.info("Spring params is welcome");
        return "/WEB-INF/jsp/welcome";
    }
}

This code defines a controller method that only accepts POST requests, but in practice, it encounters errors stating that GET method is not supported. The root cause lies in the mismatch between HTTP request methods and controller configuration.

HTTP Methods Detailed Explanation

The HTTP protocol defines multiple request methods, each with specific semantics:

In web browsers, entering URLs directly in the address bar initiates GET requests, while form submissions can specify request methods through the method attribute.

Solution Implementation

The most direct solution for the aforementioned problem is to modify the method parameter in the @RequestMapping annotation:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String welcome() {
    logger.info("Spring params is welcome");
    return "/WEB-INF/jsp/welcome";
}

Alternatively, if multiple HTTP methods need to be supported, array format can be used:

@RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST})
public String welcome() {
    logger.info("Spring params is welcome");
    return "/WEB-INF/jsp/welcome";
}

SpringMVC Request Processing Mechanism

SpringMVC uses DispatcherServlet to handle all incoming HTTP requests. When a request arrives, DispatcherServlet will:

  1. Find matching HandlerMapping based on request URL
  2. Invoke corresponding controller methods through HandlerAdapter
  3. Throw HttpRequestMethodNotSupportedException if no matching request method is found

This process can be understood through the following pseudo-code:

public class DispatcherServlet {
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) {
        HandlerExecutionChain mappedHandler = getHandler(request);
        if (mappedHandler == null) {
            // No matching handler found
            return;
        }
        
        HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
        if (!ha.supports(mappedHandler.getHandler())) {
            // Unsupported handling method
            throw new HttpRequestMethodNotSupportedException(request.getMethod());
        }
        
        // Execute actual controller method
        ModelAndView mv = ha.handle(request, response, mappedHandler.getHandler());
    }
}

Frontend Form Configuration

Ensuring consistency between frontend form's method attribute and backend controller configuration is crucial:

<form action="<%=request.getContextPath() %>/test" method="post">
    <input type="submit" value="submit"> 
</form>

If the form is configured with POST method but the controller only accepts GET method, the same 405 error will occur.

Advanced Solutions

Beyond modifying the method parameter, consider the following solutions:

1. Using Composite Annotations

@PostMapping("/test")
public String welcome() {
    logger.info("Spring params is welcome");
    return "/WEB-INF/jsp/welcome";
}

2. Global Exception Handling

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
        return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)
                .body("Request method not supported, please check HTTP method configuration");
    }
}

Related Case Extensions

Similar issues can occur in other scenarios. For example, when integrating Swagger UI, improper path mapping configuration can also lead to 405 errors. This is typically caused by path conflicts or filter configuration issues.

In Swagger UI cases, problems often arise when endpoints with path "/**" conflict with request mappings of other annotations. In such situations, careful examination of request mapping priorities and path matching rules is necessary.

Best Practice Recommendations

To avoid HTTP 405 errors, follow these best practices:

Conclusion

HTTP 405 errors in SpringMVC are typically caused by mismatches between request methods and controller configurations. By deeply understanding HTTP protocol and SpringMVC's request processing mechanism, developers can effectively prevent and resolve such issues. Proper configuration and good programming practices are key to ensuring stable operation of web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.