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:
- GET: Used to retrieve resources without side effects
- POST: Used to submit data, typically with side effects
- PUT: Used to update resources
- DELETE: Used to delete resources
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:
- Find matching HandlerMapping based on request URL
- Invoke corresponding controller methods through HandlerAdapter
- 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:
- Explicitly specify supported HTTP methods when defining @RequestMapping
- Use composite annotations like @GetMapping, @PostMapping to improve code readability
- Maintain HTTP method consistency between frontend and backend
- Configure path mappings properly to avoid conflicts
- Implement global exception handling to provide user-friendly error messages
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.