Explore the application scenarios and solutions of 4xx status codes in the HTTP protocol
Introduction:
In Web development, the HTTP protocol plays a very important role. It defines the rules and conventions for communication between clients and servers. Among them, the status code is an identifier used by the server to convey the request processing status to the client. In the HTTP protocol, 4xx status codes indicate that an error occurred on the client side. This article will explore the application scenarios and solutions of 4xx status codes, and provide relevant code examples.
1. Application scenarios:
400 Bad Request: Indicates that the client submitted an invalid request.
401 Unauthorized: Indicates that the client is not authenticated or the authentication fails.
403 Forbidden: Indicates that the server rejected the request.
404 Not Found: Indicates that the resource requested by the client does not exist.
@RequestMapping(value = "/example", method = RequestMethod.POST) public ResponseEntity<String> example(@RequestBody ExampleRequest request) { if (StringUtils.isBlank(request.getName())) { return ResponseEntity.badRequest().body("Name cannot be blank"); } if (!request.getAge().matches("\d+")) { return ResponseEntity.badRequest().body("Age must be a number"); } // 处理正常流程 return ResponseEntity.ok("Success"); }
public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Token"); if (StringUtils.isBlank(token)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().println("Authentication failed"); return false; } // 验证Token的合法性 // ... return true; } }
@RequestMapping(value = "/admin", method = RequestMethod.GET) @RequiresRoles("admin") public ResponseEntity<String> admin() { // 处理业务逻辑 }
@RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity<String> getResource(@PathVariable("id") String id) { // 查询资源 // 若资源不存在,则返回404 Not Found状态码 if (resource == null) { return ResponseEntity.notFound().build(); } // 处理正常流程 return ResponseEntity.ok("Success"); }
By exploring the application scenarios and solutions of 4xx status codes, we can better understand The meaning of 4xx status codes in the HTTP protocol and the ability to handle these error conditions more effectively during development. Reasonable use of 4xx status codes can provide a better user experience for the client and is also helpful for troubleshooting and repair.
The above is the detailed content of Analyze the use cases and solutions of 4xx status codes in HTTP protocol. For more information, please follow other related articles on the PHP Chinese website!