android利用okhttp3+json实现手机号验证码登录
LoginActivity:
package com.catanddog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.catanddog.Personal.entity.MyDataObject;
import com.catanddog.Personal.entity.User;
import com.catanddog.Personal.entity.UserLoginInfo;
import com.catanddog.utils.Constants;
import com.catanddog.utils.PhoneVerify;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class LoginActivity extends AppCompatActivity {
private EditText phoneEditText;
private EditText editCodeTest;
private Button buttonGetCode, buttonLogin, buttonStop, passwordLogin;
private TextView textViewForgetPassword;
private TextView textViewRegister;
private static final String LOGIN_URL = Constants.SERVER_URL + "personal/login/phone/login";
private static final String CODE_URL = Constants.SERVER_URL + "personal/login/phone";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
initViews();
/**
* 点击获取验证码
*/
buttonGetCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phone = phoneEditText.getText().toString();
boolean phoneNullTag = true;
// 判断电话号是否为空
if (phone.equals("")){
Toast.makeText(LoginActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
phoneNullTag = false;
}
boolean phoneTag = PhoneVerify.isValidPhoneNumber(phone);
if (!phoneTag && (phone.length() != 11) ){
Log.i("tag",phone);
Toast.makeText(LoginActivity.this, "电话号码格式错误", Toast.LENGTH_SHORT).show();
}
Log.i("tag", String.valueOf(phoneTag));
Log.i("tag", String.valueOf(phoneNullTag));
if (phoneTag && phoneNullTag){
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
try {
getPhoneCode();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
}
});
// 设置登录按钮的点击监听器
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phone = phoneEditText.getText().toString();
String code = editCodeTest.getText().toString();
// 判断电话号是否为空
boolean phoneNullTag = true;
if (phone.equals("")){
Toast.makeText(LoginActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
phoneNullTag = false;
}
boolean phoneTag = PhoneVerify.isValidPhoneNumber(phone);
if (!phoneTag){
Toast.makeText(LoginActivity.this, "电话号码格式错误", Toast.LENGTH_SHORT).show();
}
// 校验验证码
boolean codeNullTag = true;
// 判断验证码是否为空
if (code.equals("")){
Toast.makeText(LoginActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
codeNullTag = false;
}
boolean codeTag = PhoneVerify.isValidVerificationCode(code);
if (!codeTag){
Toast.makeText(LoginActivity.this, "验证码格式错误", Toast.LENGTH_SHORT).show();
}
if (phoneNullTag && codeNullTag && codeTag && phoneTag){
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
login();
}
}).start();
}
}
});
// 设置跳过按钮的点击监听器
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Constants.loginState = 0;
//TODO 注意,这里需要debug!!!
UserLoginInfo.getInstance().setId(1);
UserLoginInfo.getInstance().setUserName("111");
Intent intent = new Intent(LoginActivity.this, bottomNavigationViewActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("personState", 1);
// 将Bundle对象添加到Intent中
intent.putExtras(bundle);
startActivity(intent);
}
});
// 设置密码登录的点击监听器
passwordLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Constants.loginState = 1;
startActivity(new Intent(LoginActivity.this, PasswordLoginActivity.class));
}
});
}
@SuppressLint("WrongViewCast")
private void initViews() {
editCodeTest = findViewById(R.id.codeEditText);
buttonLogin = findViewById(R.id.loginButton);
passwordLogin = findViewById(R.id.passwordLoginButton);
buttonStop = findViewById(R.id.btn_login_stop);
buttonGetCode = findViewById(R.id.getCodeButton);
phoneEditText = findViewById(R.id.phoneEditText);
}
private void getPhoneCode() throws IOException {
String phone = phoneEditText.getText().toString();
//调用后端接口,设置参数
FormBody.Builder params = new FormBody.Builder();
params.add("phone", phone);
//发送请求,可以使用默认的http,这里使用okhttp请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(CODE_URL)
.post(params.build())
.build();
okhttp3.Response response = client.newCall(request).execute();//执行发送的指令
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
}
});
}
private void login() {
final String phone = phoneEditText.getText().toString().trim();
final String code = editCodeTest.getText().toString().trim();
Log.d("debug",phone + code);
// 在代码中创建一个 OkHttpClient 实例:
OkHttpClient client = new OkHttpClient();
// 自定义数据对象转换为 RequestBody
MyDataObject dataObject = new MyDataObject(phone,code,"");
Gson gson = new Gson();
String jsonStr = gson.toJson(dataObject);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonStr);
// 创建一个 Request 对象,设置传输的数据和其他的请求参数:
Request request = new Request.Builder()
.url(LOGIN_URL) // 替换为实际的服务器URL
.post(requestBody) // 使用 POST 请求方式传输数据
.build();
// 使用 OkHttpClient 发送请求,并处理响应:
// 发送请求并处理响应
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Constants.loginState = 1;
String jsonData = response.body().string();
Log.d("debug1",jsonData);
// 示例:直接访问 JSON 数据中的字段
JSONObject jsonObject = new JSONObject(jsonData);
String result = jsonObject.getString("success");
String data = jsonObject.getString("data");
if (result.equals("true")) {
// 获取已登录用户的个人信息
Gson gsonBack = new Gson();
User user = gsonBack.fromJson(data, User.class);
String userName = user.getUserName();
String signature = user.getSignature();
String avatar = user.getAvatar();
int id = user.getId();
UserLoginInfo.getInstance().setUserName(userName);
UserLoginInfo.getInstance().setAvatar(avatar);
UserLoginInfo.getInstance().setSignature(signature);
UserLoginInfo.getInstance().setId(id);
//TODO 注意,这里是临时展示
// UserLoginInfo userLoginInfo = UserLoginInfo.getInstance();
// userLoginInfo.setUserName("111");
Intent intent = new Intent(LoginActivity.this, bottomNavigationViewActivity.class);
// 创建Bundle对象,并添加数据
Bundle bundle = new Bundle();
bundle.putInt("personState", 1);
// 将Bundle对象添加到Intent中
intent.putExtras(bundle);
// 启动下一个Activity
startActivity(intent);
runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(LoginActivity.this, data, Toast.LENGTH_SHORT).show();
}
});
}
// ... 处理返回的 JSON 数据
} else {
// 处理请求失败
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="370dp"
android:layout_height="600dp"
android:layout_gravity="center_horizontal"
android:alpha="0.8"
android:orientation="vertical"
android:paddingTop="20dp"
android:layout_marginTop="40dp">
<Button
android:id="@+id/btn_login_stop"
android:layout_width="70dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:text="跳过"
android:textStyle="bold" />
<ImageView
android:layout_width="103dp"
android:layout_height="99dp"
android:layout_gravity="center"
/>
<ImageView
android:layout_width="278dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:alpha="0.6"/>
<RelativeLayout
android:id="@+id/phoneLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<EditText
android:id="@+id/phoneEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:drawablePadding="10dp"
android:hint="请输入手机号"
android:inputType="phone" />
<Button
android:id="@+id/getCodeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="获取验证码"
android:textStyle="bold" />
</RelativeLayout>
<EditText
android:id="@+id/codeEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phoneLayout"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
android:drawablePadding="10dp"
android:hint="请输入验证码"
android:inputType="number" />
<Button
android:id="@+id/passwordLoginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="20dp"
android:text="密码登录"
android:textSize="16dp"
android:textColor="#FF000000" />
<Button
android:id="@+id/loginButton"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="@id/codeEditText"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:text="登录"
android:textSize="25dp"
android:textColor="@color/black" />
</LinearLayout>
</LinearLayout>
后端:采用mybatisPlus+mysql+springboot+redis
Controller:
package com.catanddogdiary.personal.controller;
import com.catanddogdiary.personal.entity.Address;
import com.catanddogdiary.personal.entity.User;
import com.catanddogdiary.personal.service.AddressService;
import com.catanddogdiary.personal.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.xml.transform.Result;
import java.util.List;
@RestController
@RequestMapping("/personal")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private AddressService addressService;
/**
* 校验手机号获取验证码
* @return
* @param phone
* @param session
*/
@GetMapping("/login/phone")
@ApiOperation(value = "校验手机号获取验证码", notes = "校验手机号获取验证码")
@ApiImplicitParams({
@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query")
})
public Result loginByPhone(@RequestParam("phone") String phone, HttpSession session){
// 校验手机号,如果手机号存在,返回手机号,不存在创建一个用户
Result result = userService.sendCode(phone, session);
return result;
}
/**
* 根据手机号验证码登录
* @return
* @param phone
* @param code
*/
@GetMapping("/login/phone/login")
@ApiOperation(value = "根据手机号验证码登录", notes = "根据手机号验证码登录")
@ApiImplicitParams({
@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query")
})
public Result loginByPhone(@Param("phone") String phone,@Param("code") String code){
return userService.loginByPhone(phone,code);
}
/**
* 根据用户名密码登录
* @param user_name
* @param password
* @return
*/
@GetMapping("/login/username")
@ApiOperation(value = "根据用户名密码登录", notes = "根据用户名密码登录")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
})
public Result loginByUserName(@Param("user_name") String user_name,@Param("password") String password){
return userService.loginByUserName(user_name,password);
}
/**
* 修改用户名
* @return
* @param user_name
* @param user_id
*/
@PutMapping("/user/updateUserName")
@ApiOperation(value = "修改用户名", notes = "修改用户名")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updateUserName(
@RequestParam("user_name") String user_name,
@RequestParam("user_id") int user_id){
return userService.updateUserName(user_name,user_id);
}
/**
* 修改个性签名
* @return
* @param signature
* @param user_id
*/
@PutMapping("/user/updateSignature")
@ApiOperation(value = "修改个性签名", notes = "修改个性签名")
@ApiImplicitParams({
@ApiImplicitParam(name = "signature", value = "个性签名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updateSignature(
@RequestParam("signature") String signature,
@RequestParam("user_id") int user_id){
return userService.updateSignatureById(signature,user_id);
}
/**
* 修改密码
* @return
* @param password
* @param user_id
*/
@PutMapping("/user/updatePassword")
@ApiOperation(value = "修改密码", notes = "修改密码")
@ApiImplicitParams({
@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updatePassword(
@RequestParam("password") String password,
@RequestParam("user_id") int user_id){
return userService.updatePasswordById(password,user_id);
}
@PutMapping("/user/updateUserGender")
@ApiOperation(value = "修改性别", notes = "修改性别")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_gender", value = "性别", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updateUserGender(
@RequestParam("gender") String gender,
@RequestParam("user_id") int user_id){
return userService.updateUserGender(gender,user_id);
}
@PostMapping("/user/updateUserAvatar")
@ApiOperation(value = "修改头像", notes = "修改头像")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "头像", required = true, dataType = "MultipartFile", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updateUserAvatar(
@RequestParam(value = "file") List<MultipartFile> files,
@RequestParam("user_id") int user_id){
return userService.updateUserAvatarById(files,user_id);
}
@PutMapping("/user/updateUserBirthday")
@ApiOperation(value = "修改生日", notes = "修改生日")
@ApiImplicitParams({
@ApiImplicitParam(name = "birthday", value = "生日", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result updateUserBirthday(
@RequestParam("birthday") String birthday,
@RequestParam("user_id") int user_id){
return userService.updateUserBirthday(birthday,user_id);
}
@GetMapping("/user/getAddress")
@ApiOperation(value = "根据用户id获取地址", notes = "根据用户id获取地址")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
})
public Result getAddress(
@RequestParam("user_id") int user_id){
return addressService.getAddress(user_id);
}
@PostMapping ("/user/updateAddress")
@ApiOperation(value = "修改地址", notes = "修改地址")
@ApiImplicitParams({
@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "Address", paramType = "query")
})
public Result updateAddress(@RequestBody Address address){
return addressService.updateAddress(address);
}
@DeleteMapping("/user/deleteAddress")
@ApiOperation(value = "删除地址", notes = "删除地址")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "地址id", required = true, dataType = "int", paramType = "query")
})
public Result deleteAddress(
@RequestParam("id") int id){
return addressService.deleteAddress(id);
}
@PostMapping("/user/insertAddress")
@ApiOperation(value = "添加地址", notes = "添加地址")
@ApiImplicitParams({
@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "Address", paramType = "query")
})
public Result insertAddress(@RequestBody Address address){
return addressService.insertAddress(address);
}
@PostMapping("/username/register")
@ApiOperation(value = "用户注册", notes = "用户注册")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
})
public Result register(
@RequestParam("user_name") String user_name,
@RequestParam("password") String password){
return userService.register(user_name,password);
}
}
Service:
package com.catanddogdiary.personal.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.catanddogdiary.personal.entity.User;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.multipart.MultipartFile;
import javax.swing.plaf.multi.MultiListUI;
import javax.xml.transform.Result;
import java.util.List;
public interface UserService extends IService<User> {
/**
* 根据手机号验证码登录
* @param phone 手机号
* @param code 验证码
* @return 用户信息
*/
Result loginByPhone(String phone, String code);
/**
* 根据手机号获取验证码
* @param phone 手机号
* @param session session
* @return 验证码
*/
Result sendCode(String phone, HttpSession session);
/**
* 根据userid修改用户名
* @param userName
* @param userId
* @return 用户信息
*/
Result updateUserName(String userName, int userId);
/**
* 根据用户名密码登录
* @param userName 用户名
* @param password 密码
* @return 用户信息
*/
Result loginByUserName(String userName, String password);
/**
* 根据userid修改用户签名
* @param signature 签名
* @param userId 用户id
* @return 用户信息
*/
Result updateSignatureById(String signature, int userId);
/**
* 根据userid修改用户密码
* @param password 密码
* @param userId 用户id
* @return 用户信息
*/
Result updatePasswordById(String password, int userId);
/**
* 根据userid修改用户性别
* @param gender 性别
* @param userId 用户id
* @return 用户信息
*/
Result updateUserGender(String gender, int userId);
/**
* 修改用户头像
* @param files
* @param userId
* @return
*/
Result updateUserAvatarById(List<MultipartFile> files, int userId);
/**
* 修改用户生日
* @param birthday
* @param userId
* @return
*/
Result updateUserBirthday(String birthday, int userId);
}
ServiceImpl:
package com.catanddogdiary.personal.service.Impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catanddogdiary.personal.entity.User;
import com.catanddogdiary.personal.mapper.UserMapper;
import com.catanddogdiary.personal.service.UserService;
import com.catanddogdiary.utils.CheckUtils;
import com.catanddogdiary.utils.RandomUtil;
import com.catanddogdiary.utils.Result;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.catanddogdiary.utils.staticClass.*;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
@ApiOperation(value = "校验手机号与验证码是否相符", notes = "校验手机号与验证码是否相符")
public Result loginByPhone(String phone, String code) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 获取redis中的验证码
String phoneKey = phone + ":code";
String phoneValue = jedis.get(phoneKey);
if(code.equals(phoneValue)){
//如果验证码和redis中的验证码一样,使用后删除redis中的验证码
jedis.del(phoneKey);
}else {
return Result.fail("手机号或验证码错误!", CODEFAIL);
}
User user = userMapper.selectByPhone(phone);
if (user != null){
return Result.success(String.valueOf(user), SUCCESS);
}else {
//新建默认用户
User newUser = new User();
newUser.setPhone(phone);
newUser.setUserName("用户" + phone);
newUser.setPassword("123456");
int id = userMapper.insertByPhone(newUser.getUserName(), newUser.getPassword(), newUser.getPhone());
return Result.success(String.valueOf(newUser), SUCCESS);
}
}
@ApiOperation(value = "校验手机号获取验证码", notes = "校验手机号获取验证码")
@Override
public Result sendCode(String phone, HttpSession session) {
// 校验手机号,如果手机号存在,返回手机号,不存在创建一个用户
if (CheckUtils.isPhoneInvalid(phone)) {
// 无效手机号,返回错误信息
return Result.fail("手机号格式有误!", PHONEFAIL);
}
// 有效生成验证码
String code = RandomUtil.randomNumbers(6);
// 模拟发送验证码
System.out.println("验证码为:" + code);
//拼接向Redis中保存的验证码的key,必须保证唯一性
String phoneKey = phone + ":code";
//创建jedis对象
Jedis jedis = new Jedis("127.0.0.1", 6379);
//向redis中保存验证码,时效为120秒
jedis.setex(phoneKey,120,code);
// 关闭jedis
jedis.close();
return Result.success("验证码为:" + code, SUCCESS);
}
@Override
@ApiOperation(value = "修改用户名", notes = "修改用户名")
public Result updateUserName(String userName, int userId) {
//校验用户名
if (!CheckUtils.isUserNameInvalid(userName)) {
// 无效用户名,返回错误信息
return Result.fail("用户名格式有误!", USERNAMEFAIL);
}
// 更新用户名
int user = userMapper.updateUserName(userName, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
Result result = Result.success("修改用户名成功!" + userName, SUCCESS);
return result;
}
@Override
@ApiOperation(value = "根据用户名密码登录", notes = "根据用户名密码登录")
public Result loginByUserName(String userName, String password) {
// 根据用户名密码登录
User user = userMapper.selectByUserName(userName);
// 判断用户名密码是否符合,校验用户名为1-20位的数字或字母
if (!CheckUtils.isUserNameInvalid(userName)) {
// 无效用户名,返回错误信息
return Result.fail("用户名格式有误!", USERNAMEFAIL);
}
if (!CheckUtils.isPasswordInvalid(password)) {
// 无效密码,返回错误信息
return Result.fail("密码格式有误!", PASSWORDFAIL);
}
// 判断用户是否存在
if (user != null) {
// 判断密码是否正确
if (user.getPassword().equals(password)) {
// 密码正确,返回用户信息
return Result.success(String.valueOf(user), SUCCESS);
} else {
// 密码错误,返回错误信息
return Result.fail("密码错误!", PASSWORDFAIL);
}
} else {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
}
@Override
@ApiOperation(value = "根据用户id修改用户签名", notes = "根据用户id修改用户签名")
public Result updateSignatureById(String signature, int userId) {
// 校验签名
if (signature.length() > 20) {
return Result.fail("签名长度不能超过20个字符!", SIGNATUREFAIL);
}
if (signature.length() < 1) {
return Result.fail("签名不能为空!", SIGNATUREFAIL);
}
// 更新签名
if (signature.matches("^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")) {
// 更新签名
int user = userMapper.updateSignatureById(signature, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
return Result.success("修改签名成功!" + signature, SUCCESS);
}
return Result.fail("签名只能包含数字、字母、中文!", SIGNATUREFAIL);
}
@Override
@ApiOperation(value = "根据用户id修改用户密码", notes = "根据用户id修改用户密码")
public Result updatePasswordById(String password, int userId) {
// 校验密码
if (!CheckUtils.isPasswordInvalid(password)) {
// 无效密码,返回错误信息
return Result.fail("密码格式有误!", PASSWORDFAIL);
}
// 更新密码
if (password.matches("^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")) {
// 更新密码
int user = userMapper.updatePasswordById(password, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
return Result.success("修改密码成功!" + password, SUCCESS);
}
return Result.fail("密码只能包含数字、字母!", PASSWORDFAIL);
}
@Override
@ApiOperation(value = "根据用户id修改用户性别", notes = "根据用户id修改用户性别")
public Result updateUserGender(String gender, int userId) {
if (gender.equals("男") || gender.equals("女")) {
// 更新性别
int user = userMapper.updateUserGender(gender, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", GENDERFAIL);
}
return Result.success("修改性别成功!" + gender, SUCCESS);
}
return Result.fail("性别只能是男或女!", GENDERFAIL);
}
@Override
@ApiOperation(value = "根据用户id修改用户头像", notes = "根据用户id修改用户头像")
public Result updateUserAvatarById(List<MultipartFile> files, int userId) {
// 校验头像
if (files.size() > 1) {
return Result.fail("头像只能上传一个!", AVATARFAIL);
}
if (!CheckUtils.isAvatarInvalid(files.get(0).getOriginalFilename())) {
// 无效头像,返回错误信息
return Result.fail("头像格式有误!", AVATARFAIL);
}
// 获取文件名称
String avatar = files.get(0).getOriginalFilename();
// 将文件保存到本地
if (avatar != null) {
// 生成本地地址,将地址保存到数据库
String avatarUrl = "http://localhost:8080/catanddog/avatar/" + avatar;
// 将文件保存到本地地址
try {
files.get(0).transferTo(new File("G:\\IDEA2023\\CatAndDogDiaryBackEnd\\CatAndDogDiaryEnd\\CatAndDogDiaryEnd\\src\\main\\resources\\static\\avatar\\" + avatar));
} catch (IOException e) {
throw new RuntimeException(e);
}
// 更新头像
int user = userMapper.updateUserAvatarById(avatarUrl, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
return Result.success("修改头像成功!" + avatar, SUCCESS);
}
return Result.fail("头像只能包含数字、字母、中文!", AVATARFAIL);
}
@Override
@ApiOperation(value = "根据用户id修改用户生日", notes = "根据用户id修改用户生日")
public Result updateUserBirthday(String birthday, int userId) {
if (birthday.length() == 10) {
// 更新生日
int user = userMapper.updateUserBirthday(birthday, userId);
// 判断用户是否存在
if (user == 0) {
// 用户不存在,返回错误信息
return Result.fail("用户不存在!", USERNAMEFAIL);
}
return Result.success("修改生日成功!" + birthday, SUCCESS);
}
return Result.fail("生日格式有误!", BIRTHDAYFAIL);
}
}