Why Validation Matters: Java Bean Validation and Permission Checks
This article explains why both front‑end and back‑end data validation are essential for secure and user‑friendly web applications, introduces Java Bean Validation annotations, shows how to integrate them with Spring MVC, and compares common Java permission‑control frameworks such as Spring Security, Shiro and Sa‑Token.
Front‑End Validation
Front‑end validation acts as a friendly gatekeeper that gives users immediate feedback on incorrect input, improving user experience and preventing obvious bad data from reaching the server.
User experience: Errors are shown instantly, allowing users to correct them on the spot.
Reduce back‑end load: Invalid or incomplete requests are filtered out early, saving bandwidth and server resources.
Typical front‑end checks include:
Required fields: Ensure mandatory inputs are not empty.
Format validation: Email pattern, 11‑digit phone numbers, etc., usually via regular expressions.
Duplicate input: Confirm password matches the original password.
Range/length validation: Age must be non‑negative; password length between 6 and 20 characters.
Business validation: Username uniqueness, product stock availability – often needs back‑end cooperation.
File upload validation: Restrict file types (e.g., .jpg, .png) and size limits.
Security validation: Basic XSS mitigation by escaping user‑provided content.
The core goal is to guide users to correct input and enhance interaction experience.
Back‑End Validation
Back‑end validation is the final defensive line; it must assume that any data coming from the client could be malicious and therefore re‑validate everything that the front‑end already checked.
Integrity check: Required fields such as userId or orderId must be present; missing fields trigger an immediate error response.
Existence/legitimacy check: Verify that identifiers like productId actually exist in the database and that coupons are not expired.
Consistency check: Ensure that state transitions obey business rules (e.g., an order cannot move directly from "unpaid" to "completed").
Security check: Guard against XSS, SQL injection, etc., by using parameterized queries and output escaping.
Manually writing if‑else for each check is tedious; Java provides the Bean Validation (JSR‑303/349/380) specification to declare constraints directly on POJOs.
Bean Validation annotations
@NotNull: Value must not be null. @NotEmpty: Collection/array/string must not be null and size > 0. @NotBlank: String must contain at least one non‑whitespace character. @Null: Value must be null. @AssertTrue / @AssertFalse: Boolean must be true/false. @Min(value) / @Max(value): Numeric value must be ≥ / ≤ the given limit. @DecimalMin / @DecimalMax: Same as @Min/@Max but for BigDecimal and other decimal types. @Size(min=, max=): Length of a string, collection, map or array must be within the specified range. @Digits(integer=, fraction=): Limits the number of integer and fractional digits. @Pattern(regexp=, flags=): String must match the supplied regular expression. @Email: Validates that a string conforms to an email address format. @Past / @Future / @PastOrPresent / @FutureOrPresent: Date/time must be before/after or equal to the current moment.
Typical Maven dependency (Spring Boot 2.3+):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Example DTO with validation annotations:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
@NotNull(message = "classId cannot be null")
private String classId;
@Size(max = 33)
@NotNull(message = "name cannot be null")
private String name;
@Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex value not allowed")
@NotNull(message = "sex cannot be null")
private String sex;
@Email(message = "invalid email format")
@NotNull(message = "email cannot be null")
private String email;
}Controller method using @Valid:
@RestController
@RequestMapping("/api")
public class PersonController {
@PostMapping("/person")
public ResponseEntity<Person> createPerson(@RequestBody @Valid Person person) {
return ResponseEntity.ok().body(person);
}
@GetMapping("/person/{id}")
public ResponseEntity<Integer> getPersonById(@PathVariable @Max(value = 5, message = "ID cannot exceed 5") Integer id) {
return ResponseEntity.ok().body(id);
}
@GetMapping("/person")
public ResponseEntity<String> findPersonByName(@RequestParam @NotBlank(message = "Name required") @Size(max = 10, message = "Name too long") String name) {
return ResponseEntity.ok().body("Found person: " + name);
}
}Note: The controller class must be annotated with @Validated to enable method‑parameter validation.
Permission Validation
After data has been validated, permission validation determines whether the currently authenticated user is allowed to perform the requested operation on the target resource.
Prevent unauthorized actions (e.g., a regular user editing another user's order).
Enforce business isolation by role (admin vs. guest vs. VIP).
Meet regulatory compliance requirements.
Common Java security frameworks:
Spring Security (recommended): Filter‑chain based authentication and authorization, highly configurable but with a steep learning curve.
Apache Shiro: Lightweight, intuitive API, suitable for non‑Spring projects.
Sa‑Token: Chinese‑origin lightweight framework with built‑in SSO, token renewal, and easy configuration.
Manual checks (not recommended for complex scenarios): Directly retrieve the current user from SecurityContextHolder and perform if‑else role checks, which couples security logic with business code.
Two typical access‑control models:
RBAC (Role‑Based Access Control): Assign roles to users and permissions to roles; the user inherits all permissions of their roles.
ABAC (Attribute‑Based Access Control): Decisions are based on user, resource, action, and environment attributes, offering finer granularity at the cost of complexity.
Summary
Front‑end validation: Improves user experience and filters out obvious bad data before it reaches the server.
Back‑end validation: Guarantees data integrity and business rule compliance using Bean Validation annotations.
Permission validation: Ensures that only authorized users can perform specific actions; frameworks like Spring Security, Shiro, and Sa‑Token simplify implementation.
References
Why front‑end and back‑end validation are both required: https://juejin.cn/post/7306045519099658240
Detailed design of permission systems: https://javaguide.cn/system-design/security/design-of-authority-system.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
