Handling Interface Parameters in Spring Boot: Retrieval, Types, Validation, and File Upload

This article explains how to retrieve and handle various Spring Boot API parameters—including query, path, request body, header, and file uploads—covers parameter type handling such as dates and lists, demonstrates validation annotations, and provides complete code examples for each scenario.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Handling Interface Parameters in Spring Boot: Retrieval, Types, Validation, and File Upload

In this tutorial the author, a seasoned backend Java developer, shares practical techniques for designing and debugging Spring Boot API endpoints, focusing on how interface parameters are obtained, validated, and processed.

Parameter retrieval can occur from query strings, request bodies, path variables, headers, or cookies. Simple method‑parameter examples are shown:

@GetMapping("/testParams1")
public ResponseEntity<String> testParams1(String param1, Integer param2) {
    return ResponseEntity.ok(MessageFormat.format("param1:[{0}];param2:[{1}]", param1, param2));
}

When using a request object, the controller receives a populated POJO:

@GetMapping("/testParams2")
public ResponseEntity<String> testParams2(ParamsReq paramsReq) {
    return ResponseEntity.ok(MessageFormat.format("param1:[{0}];param2:[{1}]", paramsReq.getParam1(), paramsReq.getParam2()));
}

The ParamsReq class contains standard getters, setters, and a toString method.

public class ParamsReq {
    private String param1;
    private String param2;
    // constructors, getters, setters, toString omitted for brevity
}

For POST requests the same object can be used, but when the request body is JSON the @RequestBody annotation is required:

public ResponseEntity<String> testParams3(@RequestBody ParamsReq paramsReq) { ... }

Path variables are accessed with @PathVariable:

@GetMapping("/testParams4/{pathParam}")
public ResponseEntity<String> testParams4(@PathVariable("pathParam") String pathParam) {
    return ResponseEntity.ok(MessageFormat.format("pathParam:[{0}];", pathParam));
}

Header and cookie parameters are rarely used for business data and are mentioned only briefly.

Parameter types include:

Numbers and strings – no special handling.

Dates – require @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") to bind a string to a Date object.

Lists – must be annotated with @RequestParam("paramList") List<Integer> paramList and supplied as a comma‑separated query value.

File uploads – an HTML form with enctype="multipart/form-data" posts to a controller method that receives a MultipartFile annotated with @RequestParam("file").

<!-- upload.html -->
<!DOCTYPE html>
<html>
<head><title>File Upload Demo</title></head>
<body>
<h1>File Upload Demo</h1>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <br/><br/>
    <input type="submit" value="Upload" />
</form>
</body>
</html>
<!-- FileUploadController.java -->
@Controller
public class FileUploadController {
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
        }
        try {
            byte[] bytes = file.getBytes();
            // save bytes to storage
            return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Validation of incoming parameters is performed with the standard javax.validation annotations. After adding the validation-api dependency, common constraints such as @NotNull, @NotBlank, @NotEmpty, @Max, @Min, @Pattern, @Email, etc., can be placed on fields of a request DTO.

@Data
public class StudentReq {
    @NotBlank(message = "主键不能为空")
    private String id;
    @NotBlank(message = "名字不能为空")
    @Size(min = 2, max = 4, message = "名字字符长度必须为 2~4个")
    private String name;
    @Pattern(regexp = "^1[3456789]\d{9}$", message = "手机号格式错误")
    private String phone;
    @Email(message = "邮箱格式错误")
    private String email;
    @Past(message = "生日必须早于当前时间")
    private Date birth;
    @Min(value = 0, message = "年龄必须为 0~100")
    @Max(value = 100, message = "年龄必须为 0~100")
    private Integer age;
    @PositiveOrZero
    private Double score;
}

Finally, the article lists several objects that Spring can inject directly into controller method parameters, such as HttpServletRequest, HttpServletResponse, HttpSession, Principal, Model, BindingResult, Locale, MultipartFile, and others, emphasizing their frequent use in real‑world backend development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javabackend-developmentvalidationSpring Bootfile uploadAPI parameters
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.