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 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 { @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 handlemethodargumentnotvalid(methodargumentnotvalidexception ex, httpheaders headers, httpstatus status, webrequest request) { map body = new linkedhashmap(); body.put(timestamp, localdatetime.now()); body.put(status, status.value()); // get all errors list 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我们使用 junit 5 编写一个测试来验证具有无效电子邮件地址的“用户”对象。然后我们使用 validator 接口来验证 user 对象并检查是否返回了预期的验证错误。
10 考虑客户端验证客户端验证可以通过向用户提供即时反馈并减少对服务器的请求数量来改善用户体验。但是,不应依赖它作为验证输入的唯一方法。客户端验证很容易被绕过或操纵,因此必须在服务器端验证输入,以确保安全性和数据完整性。
总结有效的验证对于任何 web 应用程序的稳定性和安全性都是必不可少的。spring boot 提供了一套工具和库来简化验证逻辑并使其更易于维护。通过遵循本文中讨论的最佳实践,您可以确保您的验证组件有效并提供出色的用户体验。
未来智能交通!绝对是首尾相连的汽车
鲸小爱英语:解决青年大学生“哑巴口语”,Mobile+AI的结合
4610-050-060加速度传感器安装注意事项
区块链在政府中的应用潜力
国内智能语音识别产业的增长,可能源于三大技术突破
SpringBoot参数验证的10个技巧2
华为p20能升鸿蒙吗_华为p40 pro更新鸿蒙系统
英特尔未来12到18个月将持续改良14纳米
地平线与比亚迪举行战略合作签约仪式,加速智能汽车落地
覆铜板是下游PCB的核心材料,也是PCB原材料成本最高的
小米12是小屏手机吗_小米12屏幕到底多大
千方科技荣登“2022新型实体企业100强榜单”
科技新闻精选:.国产超分辨光刻装备通过验收,可加工22纳米芯片
OPPO定制机玩出时尚范儿,oppoR11巴萨限量版撞色惊艳
5G前传网络构建的作用
中国AI产业火热,AI商业化突破口何在?
深度分析PLC与变频器连接问题
X射线的无损检测技术应用介绍
以色列将在未来改变世界的十大创新技术
加密引擎增速12倍的FPGA技术