private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$"; //手机号验证正则表达式 private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; @Override public User loginService(LoginParams loginParams) { //查询条件 QueryWrapper<User> queryWrapper = new QueryWrapper<>(); Matcher emailMatcher = Pattern.compile(EMAIL_REGEX).matcher(loginParams.getUserAccount()); Matcher phoneMatcher = Pattern.compile(PHONE_REGEX).matcher(loginParams.getUserAccount()); //格式匹配邮箱 if (emailMatcher.matches()) { queryWrapper.eq("user_email",loginParams.getUserAccount()) .eq("user_password",MD5Utils.inputPassToFormPass(loginParams.getUserPassword())); } //格式匹配手机号 else if (phoneMatcher.matches()) { queryWrapper.eq("user_phone",loginParams.getUserAccount()) .eq("user_password",MD5Utils.inputPassToFormPass(loginParams.getUserPassword())); } //均不匹配则验证用户名 else { queryWrapper.eq("user_account",loginParams.getUserAccount()) .eq("user_password",MD5Utils.inputPassToFormPass(loginParams.getUserPassword())); } return userMapper.selectOne(queryWrapper); }
时间: 2024-03-16 12:42:38 浏览: 169
Regex-Blocklist:Firefox插件,用于基于正则表达式阻止URL
您的代码看起来非常简洁和易于阅读。这里有一些可以提高代码可读性和性能的建议:
1. 将正则表达式的编译移到类的静态初始化块中,以避免在每次方法调用时重新编译正则表达式。
2. 使用常量代替魔法数字或字符串,以提高代码的可维护性。
3. 在查询用户时,可以使用 Lambda 表达式来简化查询条件。
下面是优化后的代码:
```java
private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
// 编译正则表达式
private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
@Override
public User loginService(LoginParams loginParams) {
// 查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// 格式匹配邮箱
Matcher emailMatcher = EMAIL_PATTERN.matcher(loginParams.getUserAccount());
if (emailMatcher.matches()) {
queryWrapper.lambda().eq(User::getUserEmail, loginParams.getUserAccount())
.eq(User::getUserPassword, MD5Utils.inputPassToFormPass(loginParams.getUserPassword()));
}
// 格式匹配手机号
else if (PHONE_PATTERN.matcher(loginParams.getUserAccount()).matches()) {
queryWrapper.lambda().eq(User::getUserPhone, loginParams.getUserAccount())
.eq(User::getUserPassword, MD5Utils.inputPassToFormPass(loginParams.getUserPassword()));
}
// 均不匹配则验证用户名
else {
queryWrapper.lambda().eq(User::getUserAccount, loginParams.getUserAccount())
.eq(User::getUserPassword, MD5Utils.inputPassToFormPass(loginParams.getUserPassword()));
}
return userMapper.selectOne(queryWrapper);
}
```
希望这些建议能够帮助到您!
阅读全文