一些最常用的验证注释包括:
@notnull:指定字段不能为空。
@notempty:指定列表字段不能为空。
@notblank:指定字符串字段不得为空或仅包含空格。
@min 和 @max:指定数字字段的最小值和最大值。
@pattern:指定字符串字段必须匹配的正则表达式模式。
@email:指定字符串字段必须是有效的电子邮件地址。
具体用法参考下面例子:
public class user { @notnull private long id; @notblank @size(min = 2, max = 50) private string firstname; @notblank @size(min = 2, max = 50) private string lastname; @email private string email; @notnull @min(18) @max(99) private integer age; @notempty private list<string> hobbies; @pattern(regexp = "[a-z]{2}\d{4}") private string employeeid;
2.使用自定义验证注解虽然 spring boot 的内置验证注释很有用,但它们可能无法涵盖所有情况。如果有特殊参数验证的场景,可以使用 spring 的 jsr 303 验证框架创建自定义验证注释。自定义注解可以让你的的验证逻辑更具可重用性和可维护性。
假设我们有一个应用程序,用户可以在其中创建帖子。每个帖子都应该有一个标题和一个正文,并且标题在所有帖子中应该是唯一的。虽然 spring boot 提供了用于检查字段是否为空的内置验证注释,但它没有提供用于检查唯一性的内置验证注释。在这种情况下,我们可以创建一个自定义验证注解来处理这种情况。
首先,我们创建自定义约束注解uniquetitle :
@target({elementtype.field})@retention(retentionpolicy.runtime)@constraint(validatedby = uniquetitlevalidator.class)public @interface uniquetitle { string message() default "title must be unique"; class<?>[] groups() default {}; class<? extends payload>[] payload() default {};}
接下来,我们创建一个postrepository接口,目的是从数据库中检索帖子:
public interface postrepository extends jparepository<post, long> { post findbytitle(string title);}
然后我们需要定义验证器类 uniquetitlevalidator,如下所示:
@componentpublic class uniquetitlevalidator implements constraintvalidator<uniquetitle, string> { @autowired private postrepository postrepository; @override public boolean isvalid(string title, constraintvalidatorcontext context) { if (title == null) { return true; } return objects.isnull(postrepository.findbytitle(title)); }}
uniquetitlevalidator实现了constraintvalidator接口,它有两个泛型类型:第一个是自定义注解uniquetitle,第二个是正在验证的字段类型(在本例中为string). 我们还自动装配了postrepository 类以从数据库中检索帖子。
isvalid()方法通过查询 postrepository 来检查 title 是否为 null 或者它是否是唯一的。如果 title 为 null 或唯一,则验证成功,并返回 true。
定义了自定义验证注释和验证器类后,我们现在可以使用它来验证 spring boot 应用程序中的帖子标题:
public class post { @uniquetitle private string title; @notnull private string body;}
我们已将 @uniquetitle 注释应用于 post 类中的 title 变量。验证此字段时,这将触发 uniquetitlevalidator 类中定义的验证逻辑。
3.在服务器端验证除了前端或者客户端做了验证意外,服务器端验证输入是至关重要的。它可以确保在处理或存储任何恶意或格式错误的数据之前将其捕获,这对于应用程序的安全性和稳定性至关重要。
假设我们有一个允许用户创建新帐户的 rest 端点。端点需要一个包含用户用户名和密码的 json 请求体。为确保输入有效,我们可以创建一个 dto(数据传输对象)类并将验证注释应用于其字段:
public class userdto { @notblank private string username; @notblank private string password;}
我们使用@notblank注解来确保username和password字段不为空或 null。
接下来,我们可以创建一个控制器方法来处理 http post 请求并在创建新用户之前验证输入:
@restcontroller@requestmapping("/users")@validatedpublic class usercontroller { @autowired private userservice userservice; @postmapping public responseentity<string> createuser(@valid @requestbody userdto userdto) { userservice.createuser(userdto); return responseentity.status(httpstatus.created).body("user created successfully"); }}
我们使用 spring 的@validated注解来启用方法级验证,我们还将 @valid 注释应用于 userdto 参数以触发验证过程。
4.提供有意义的错误信息当验证失败时,必须提供清晰简洁的错误消息来描述出了什么问题以及如何修复它。
这是一个示例,如果我们有一个允许用户创建新用户的 restful api。我们要确保姓名和电子邮件地址字段不为空,年龄在 18 到 99 岁之间,除了这些字段,如果用户尝试使用重复的“用户名”创建帐户,我们还会提供明确的错误消息或“电子邮件”。
为此,我们可以定义一个带有必要验证注释的模型类 user,如下所示:
public class user { @notblank(message = "用户名不能为空") private string name; @notblank(message = "email不能为空") @email(message = "无效的emaild地址") private string email; @notnull(message = "年龄不能为空") @min(value = 18, message = "年龄必须大于18") @max(value = 99, message = "年龄必须小于99") private integer age;}
我们使用 message属性为每个验证注释提供了自定义错误消息。
接下来,在我们的 spring 控制器中,我们可以处理表单提交并使用 @valid 注释验证用户输入:
@restcontroller@requestmapping("/users")public class usercontroller { @autowired private userservice userservice; @postmapping public responseentity<string> createuser(@valid @requestbody user user, bindingresult result) { if (result.haserrors()) { list<string> errormessages = result.getallerrors().stream() .map(defaultmessagesourceresolvable::getdefaultmessage) .collect(collectors.tolist()); return responseentity.badrequest().body(errormessages.tostring()); } // save the user to the database using userservice userservice.saveuser(user); return responseentity.status(httpstatus.created).body("user created successfully"); }}
我们使用 @valid 注释来触发 user 对象的验证,并使用 bindingresult 对象来捕获任何验证错误。
5.将 i18n 用于错误消息如果你的应用程序支持多种语言,则必须使用国际化 (i18n) 以用户首选语言显示错误消息。
以下是在 spring boot 应用程序中使用 i18n 处理错误消息的示例
首先,在资源目录下创建一个包含默认错误消息的 messages.properties 文件
# messages.propertiesuser.name.required=name is required.user.email.invalid=invalid email format.user.age.invalid=age must be a number between 18 and 99.
接下来,为每种支持的语言创建一个 messages_xx.properties 文件,例如,中文的 messages_zh_cn.properties。
user.name.required=名称不能为空.user.email.invalid=无效的email格式.user.age.invalid=年龄必须在18到99岁之间.
然后,更新您的验证注释以使用本地化的错误消息
public class user { @notnull(message = "{user.id.required}") private long id; @notblank(message = "{user.name.required}") private string name; @email(message = "{user.email.invalid}") private string email; @notnull(message = "{user.age.required}") @min(value = 18, message = "{user.age.invalid}") @max(value = 99, message = "{user.age.invalid}") private integer age;}
最后,在 spring 配置文件中配置 messagesource bean 以加载 i18n 消息文件
@configurationpublic class appconfig { @bean public messagesource messagesource() { resourcebundlemessagesource messagesource = new resourcebundlemessagesource(); messagesource.setbasename("messages"); messagesource.setdefaultencoding("utf-8"); return messagesource; } @bean public localvalidatorfactorybean validator() { localvalidatorfactorybean validatorfactorybean = new localvalidatorfactorybean(); validatorfactorybean.setvalidationmessagesource(messagesource()); return validatorfactorybean; }}
现在,当发生验证错误时,错误消息将根据随请求发送的“accept-language”标头以用户的首选语言显示。
6.使用分组验证验证组是 spring boot 验证框架的一个强大功能,允许您根据其他输入值或应用程序状态应用条件验证规则。
现在有一个包含三个字段的user类的情况下:firstname、lastname和email。我们要确保如果 email 字段为空,则 firstname 或 lastname 字段必须非空。否则,所有三个字段都应该正常验证。
为此,我们将定义两个验证组:emailnotempty 和 default。emailnotempty 组将包含当 email 字段不为空时的验证规则,而 default 组将包含所有三个字段的正常验证规则。
创建带有验证组的 user 类
public class user { @notblank(groups = default.class) private string firstname; @notblank(groups = default.class) private string lastname; @email(groups = emailnotempty.class) private string email; // getters and setters omitted for brevity public interface emailnotempty {} public interface default {}}
请注意,我们在user类中定义了两个接口,emailnotempty和 default。这些将作为我们的验证组。
接下来,我们更新controller使用这些验证组
@restcontroller@requestmapping("/users")@validatedpublic class usercontroller { public responseentity<string> createuser( @validated({org.example.model.ex6.user.emailnotempty.class}) @requestbody user userwithemail, @validated({user.default.class}) @requestbody user userwithoutemail) { // create the user and return a success response }}
我们已将@validated注释添加到我们的控制器,表明我们想要使用验证组。我们还更新了 createuser 方法,将两个 user 对象作为输入,一个在 email 字段不为空时使用,另一个在它为空时使用。
@validated 注释用于指定将哪个验证组应用于每个 user 对象。对于 userwithemail 参数,我们指定了 emailnotempty 组,而对于 userwithoutemail 参数,我们指定了 default 组。
进行这些更改后,现在将根据“电子邮件”字段是否为空对“用户”类进行不同的验证。如果为空,则 firstname 或 lastname 字段必须非空。否则,所有三个字段都将正常验证。
7.对复杂逻辑使用跨域验证如果需要验证跨多个字段的复杂输入规则,可以使用跨字段验证来保持验证逻辑的组织性和可维护性。跨字段验证可确保所有输入值均有效且彼此一致,从而防止出现意外行为。
假设我们有一个表单,用户可以在其中输入任务的开始日期和结束日期,并且我们希望确保结束日期不早于开始日期。我们可以使用跨域验证来实现这一点。
首先,我们定义一个自定义验证注解enddateafterstartdate:
@target({elementtype.type})@retention(retentionpolicy.runtime)@constraint(validatedby = enddateafterstartdatevalidator.class)public @interface enddateafterstartdate { string message() default "end date must be after start date"; class<?>[] groups() default {}; class<? extends payload>[] payload() default {};}
然后,我们创建验证器enddateafterstartdatevalidator:
public class enddateafterstartdatevalidator implements constraintvalidator<enddateafterstartdate, taskform> { @override public boolean isvalid(taskform taskform, constraintvalidatorcontext context) { if (taskform.getstartdate() == null || taskform.getenddate() == null) { return true; } return taskform.getenddate().isafter(taskform.getstartdate()); }}
最后,我们将enddateafterstartdate注释应用于我们的表单对象taskform:
@enddateafterstartdatepublic class taskform { @notnull @datetimeformat(pattern = "yyyy-mm-dd") private localdate startdate; @notnull @datetimeformat(pattern = "yyyy-mm-dd") private localdate enddate;}
现在,当用户提交表单时,验证框架将自动检查结束日期是否晚于开始日期,如果不是,则提供有意义的错误消息。
8.对验证错误使用异常处理可以使用异常处理exceptionhandler来统一捕获和处理验证错误。
以下是如何在 spring boot 中使用异常处理来处理验证错误的示例:
@restcontrolleradvicepublic class restexceptionhandler extends responseentityexceptionhandler { @exceptionhandler(methodargumentnotvalidexception.class) protected responseentity<object> handlemethodargumentnotvalid(methodargumentnotvalidexception ex, httpheaders headers, httpstatus status, webrequest request) { map<string, object> body = new linkedhashmap<>(); body.put("timestamp", localdatetime.now()); body.put("status", status.value()); // get all errors list<string> errors = ex.getbindingresult() .getfielderrors() .stream() .map(x -> x.getdefaultmessage()) .collect(collectors.tolist()); body.put("errors", errors); return new responseentity<>(body, headers, status); }}
在这里,我们创建了一个用 @restcontrolleradvice 注解的 restexceptionhandler 类来处理我们的 rest api 抛出的异常。然后我们创建一个用 @exceptionhandler 注解的方法来处理在验证失败时抛出的 methodargumentnotvalidexception。
在处理程序方法中,我们创建了一个 map 对象来保存错误响应的详细信息,包括时间戳、http 状态代码和错误消息列表。我们使用 methodargumentnotvalidexception 对象的 getbindingresult() 方法获取所有验证错误并将它们添加到错误消息列表中。
最后,我们返回一个包含错误响应详细信息的responseentity对象,包括作为响应主体的错误消息列表、http 标头和 http 状态代码。
有了这个异常处理代码,我们的 rest api 抛出的任何验证错误都将被捕获并以结构化和有意义的格式返回给用户,从而更容易理解和解决问题。
9.测试你的验证逻辑需要为你的验证逻辑编写单元测试,以帮助确保它正常工作。
@datajpatestpublic class uservalidationtest { @autowired private testentitymanager entitymanager; @autowired private validator validator; @test public void testvalidation() { user user = new user(); user.setfirstname("john"); user.setlastname("doe"); user.setemail("invalid email"); set<constraintviolation<user>> violations = validator.validate(user); assertequals(1, violations.size()); assertequals("must be a well-formed email address", violations.iterator().next().getmessage()); }}
我们使用 junit 5 编写一个测试来验证具有无效电子邮件地址的“用户”对象。然后我们使用 validator 接口来验证 user 对象并检查是否返回了预期的验证错误。
10.考虑客户端验证客户端验证可以通过向用户提供即时反馈并减少对服务器的请求数量来改善用户体验。但是,不应依赖它作为验证输入的唯一方法。客户端验证很容易被绕过或操纵,因此必须在服务器端验证输入,以确保安全性和数据完整性。
以上就是springboot参数验证的技巧有哪些的详细内容。
