java - 检查重复的用户名阻止更新用户
问题描述
我有以下用于添加用户的 Java 控制器:
@GetMapping("/registration")
public String registration(Model model) {
if (securityService.isAuthenticated()) {
return "redirect:/";
}
model.addAttribute("userForm", new User());
return "registration";
}
我还有以下验证器来防止重复的用户名:
if (userService.findByEmail(user.getEmail()) != null) {
errors.rejectValue("username", "Duplicate.userForm.username");
}
我现在正在尝试添加一个控制器来更新现有用户。我创建了以下内容以使用与创建用户时相同的注册表单:
@GetMapping("/users/showFormForUpdate")
public String showFormForUpdate(@RequestParam("userId") long theId, Model theModel) {
User theUser = userService.findById(theId);
theModel.addAttribute("userForm", theUser);
return "registration";
}
我的问题是,当我尝试更新我的重复用户时,如果我不更改用户名,就会出现警报。
这是我在注册表单中发出警报的代码:
<div class="form-group">
<input type="text" th:field="*{username}" class="form-control" placeholder="Username"
autofocus="true">
<span style="color:red" class="has-error" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span>
</div>
总之,当我创建用户时,我希望标记任何重复的用户名,但如果我正在更新用户,我不希望这样。我如何更新我的用户但保持防止重复用户的能力?我正在使用addAttribute
. org.springframework.ui.Model
我知道一种选择是使用不同的形式进行更新,但我希望应该有一种方法可以同时使用一种形式。
解决方案
if (userService.findByEmail(user.getEmail()) != null) { errors.rejectValue("username", "Duplicate.userForm.username"); }
避免上面的代码级别验证,如果用户名重复,让数据库抱怨。即在注册过程中,因为该User
对象没有userId
,JPA 有一个insert
,如果存在重复,您将收到一个 通知DataIntegrityViolationException
。在更新期间,JPA 会执行一个,update
因为userId
存在 ,并且不会导致DataIntegrityViolationException
.
推荐阅读
- javascript - 用于比较 2 个 html 字符串的 Javascript 库,例如 freecodecamp
- c# - AD 林中的 AD 身份验证
- unity3d - unity3d 中的 SignalR
- php - 会话不在 Vue.js 和 Laravel 中存储数据
- php - 系统/缓存文件夹 codeigniter 中的缓存文件过多
- python - Matlab过滤器与深度太小的Python lfilter ValueError对象
- dialogflow-es - Dialogflow 帐户关联 - 谷歌主页
- concurrency - 在不使用身份规范的情况下自动化顺序整数 ID?
- android - 使用画布和绘画将多个文本与图像一起放置的问题
- android - Facebook 登录与 Flutter 的集成