SoFunction
Updated on 2025-05-14

Share 4 tips for SpringBoot controller return value processing

In SpringBoot application development, the return value processing of the controller is a basic but extremely important link.

Reasonable return value processing can not only improve the readability and maintainability of the code, but also optimize the front-end and back-end interactive experience.

This article will introduce four commonly used controller return value processing techniques in SpringBoot.

1. Return the ResponseEntity object

ResponseEntityIt is a class provided by the Spring framework for representing HTTP responses, which allows developers to fully control the response content, including status codes, headers and response bodies.

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        try {
            User user = (id);
            if (user == null) {
                return ().build();
            }
            return (user);
        } catch (Exception e) {
            return (HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Failed to obtain user information:" + ());
        }
    }
    
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User createdUser = (user);
        URI location = ServletUriComponentsBuilder
            .fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(())
            .toUri();
        
        return (location).body(createdUser);
    }
}

Advantages

  • Provides full control over HTTP response
  • You can flexibly set status codes, header information, etc.
  • Support chain calls, the code is concise and clear
  • Especially suitable for the development of RESTful API

Applicable scenarios

  • Scenarios where HTTP status codes need to be accurately controlled
  • Scenarios where specific response headers need to be set
  • Development of RESTful API

2. Use @ResponseBody annotation

use@ResponseBodyAnnotations (or use on a class@RestController) let Spring serialize the return value directly into the HTTP response body. This method is simple and straightforward, and is especially suitable for returning JSON or XML data.

@Controller
@RequestMapping("/api/products")
public class ProductController {
    
    @GetMapping("/{id}")
    @ResponseBody
    public Product getProduct(@PathVariable Long id) {
        return (id);
    }
    
    @GetMapping("/count")
    @ResponseBody
    public Integer getProductCount() {
        return ();
    }
    
    @GetMapping("/available")
    @ResponseBody
    public boolean isProductAvailable(@RequestParam String sku) {
        return (sku);
    }
    
    @GetMapping("/message")
    @ResponseBody
    public String getMessage() {
        return "This is a simple text message";
    }
}

Advantages

  • Concise code, no additional encapsulation required
  • Supports multiple return types (objects, collections, basic types, etc.)
  • Spring automatically handles serialization process

Applicable scenarios

  • Front-end separation architecture
  • Scenarios where you just return data without caring about HTTP status
  • Simple API endpoint

3. Return to the view and model (traditional web application)

In traditional web applications, the controller method usually returns a view name and passes data through Model or ModelAndView. This method is suitable for server-side rendering applications.

@Controller
@RequestMapping("/web")
public class WebController {
    
    @GetMapping("/users")
    public String listUsers(Model model) {
        List<User> users = ();
        ("users", users);
        ("title", "User List");
        return "user/list";  // Return the view name, corresponding to templates/user/    }
    
    @GetMapping("/dashboard")
    public ModelAndView dashboard() {
        ModelAndView mav = new ModelAndView("dashboard");
        ("stats", ());
        ("lastLogin", new Date());
        return mav;
    }
    
    // Redirection example    @PostMapping("/users/save")
    public String saveUser(User user) {
        (user);
        return "redirect:/web/users";  // Redirect to user list    }
}

Advantages

  • Web applications suitable for traditional server-side rendering
  • Seamless integration with template engines (such as Thymeleaf, Freemarker)
  • Support redirection and forwarding

Applicable scenarios

  • Traditional Web Applications
  • Pages that require server-side rendering
  • Management background and other complex form interaction scenarios

4. Encapsulate using a unified response format

In actual projects, a unified response format is usually defined, including status codes, messages, and data. This approach helps the consistency and normativeness of front-end interactions.

// Unified response entity class@Data
public class ApiResponse<T> {
    private Integer code;
    private String message;
    private T data;
    private long timestamp;
    
    public static <T> ApiResponse<T> success(T data) {
        ApiResponse<T> response = new ApiResponse<>();
        (200);
        ("The operation is successful");
        (data);
        (());
        return response;
    }
    
    public static <T> ApiResponse<T> error(Integer code, String message) {
        ApiResponse<T> response = new ApiResponse<>();
        (code);
        (message);
        (());
        return response;
    }
}

// Global response processing (optional method)@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // Decide which methods need to be processed        return true;
    }
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, 
                                 MediaType selectedContentType, 
                                 Class<? extends HttpMessageConverter<?>> selectedConverterType, 
                                 ServerHttpRequest request, ServerHttpResponse response) {
        // It is already ApiResponse type and will no longer be wrapped        if (body instanceof ApiResponse) {
            return body;
        }
        // Package responds successfully        return (body);
    }
}

// Example of controller usage@RestController
@RequestMapping("/api/v1")
public class ModernApiController {
    
    @GetMapping("/orders")
    public ApiResponse<List<Order>> getOrders() {
        List<Order> orders = ();
        return (orders);
    }
    
    @GetMapping("/customers/{id}")
    public ApiResponse<Customer> getCustomer(@PathVariable Long id) {
        try {
            Customer customer = (id);
            if (customer == null) {
                return (404, "The customer does not exist");
            }
            return (customer);
        } catch (Exception e) {
            return (500, "Server Error:" + ());
        }
    }
}

Advantages

  • Provides a unified return format, making front-end processing easier
  • Includes more metadata (status code, message, etc.)
  • It can combine global exception handling to achieve a more complete error handling mechanism
  • Improve API consistency and maintainability

Applicable scenarios

  • Enterprise-level applications
  • When large-scale projects need uniform specifications
  • Scenarios that require fine-grained error handling

Summarize

In actual projects, these tips are often used in combination.

For example, a unified response format and ResponseEntity can be used in the RESTful API, which not only provides a standardized response body, but also provides flexible control of HTTP status codes.

Choosing the appropriate return value processing method can not only improve code quality, but also improve front-end and back-end collaboration efficiency.

This is the end of this article about 4 tips for processing SpringBoot controller return value. For more related content on SpringBoot controller return value processing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!