注册
- 在UserController中声明一个(/register),接口中包括两个功能://用户名是否已被占用 //注册
public Result register(String username,String password){}
- 在UserService(接口)中,实现两个方法:
public User findByUsername(String username){}//根据用户名查询用户
public void register(String username,String password){}//注册
- 在UserMapper中,声明两个方法分别执行SQL
UserController:
~~~java
package com.di.bigevent.controller;
import com.di.bigevent.pojo.Result;
import com.di.bigevent.pojo.User;
import com.di.bigevent.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")//注册接口
public Result register(String username,String password){
User u = userService.findByUserName(username);
if(u==null){
userService.register(username,password);
return Result.success();
}else{
return Result.error("用户名已被占用");
}
}
}
UserService:
package com.di.bigevent.service;
import com.di.bigevent.pojo.User;
public interface UserService {
void register(String username, String password);
User findByUserName(String username);
}
UserServiceImpl:
package com.di.bigevent.service.impl;
import com.di.bigevent.mapper.UserMapper;
import com.di.bigevent.pojo.User;
import com.di.bigevent.service.UserService;
import com.di.bigevent.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceIml implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUserName(String username) {
User u = userMapper.findByUserName(username);
return u;
}
@Override
public void register(String username, String password) {
//用MD5工具类对密码进行加密,并存储到数据库
String md5String = Md5Util.getMD5String(password);
userMapper.add(username,md5String);
}
}
UserMapper:
package com.di.bigevent.mapper;
import com.di.bigevent.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
@Mapper
public interface UserMapper {
@Select("select * from user where username=#{username}")
User findByUserName(String username);
@Insert("insert into user(username,password,create_time,update_time)" +
" values(#{username},#{password},now(),now())")
void add(String username, String password);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?