这一期是实现用户注册功能。
1.创建数据库
打开navicat,创建数据库,库名叫store。
2.创建用户表
CREATE TABLE t_user ( uid INT AUTO_INCREMENT COMMENT '用户id', username VARCHAr(20) NOT NULL UNIQUE COMMENT '用户名', password CHAr(32) NOT NULL COMMENT '密码', salt CHAr(36) COMMENT '盐值', phone VARCHAr(20) COMMENT '电话号码', email VARCHAr(30) COMMENT '电子邮箱', gender INT COMMENT '性别:0-女,1-男', avatar VARCHAr(50) COMMENT '头像', is_delete INT COMMENT '是否删除:0-未删除,1-已删除', created_user VARCHAr(20) COMMENT '日志-创建人', created_time DATETIME COMMENT '日志-创建时间', modified_user VARCHAr(20) COMMENT '日志-最后修改执行人', modified_time DATETIME COMMENT '日志-最后修改时间', PRIMARY KEY (uid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3.idea创建项目
4.配置properties文件
spring.datasource.url=jdbc:mysql://localhost:3306/store
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper
public interface UserMapper {
Integer insert(User user);
User findByUsername(String username);
}
6。在resources的mapper中创建UserMapper.xml
INSERT INTO t_user (username, password, salt, phone, email, gender, avatar, is_delete, created_user, created_time, modified_user, modified_time) VALUES (#{username}, #{password}, #{salt}, #{phone}, #{email}, #{gender}, #{avatar}, #{isDelete}, #{createdUser}, #{createdTime}, #{modifiedUser}, #{modifiedTime})
7.测试mapper层
package com.cy.store.mapper;
import com.cy.store.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
//@RunWith(SpringRunner.class)表示启动这个单元类测试
//1.必须@test注解
//2.返回类型必须是void
//3.方法的参数列表不指定任何类型
//4.方法访问修饰符必须是public
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperTests {
@Autowired
private UserMapper userMapper;
@Test
public void insert(){
System.out.println(userMapper);
User user = new User();
user.setPassword("111");
user.setUsername("777");
System.out.println(user);
System.out.println("====================================================");
Integer rows = userMapper.insert(user);
System.out.println(rows);
}
@Test
public void selectbyusername(){
User user = userMapper.findByUsername("666");
System.out.println(user);
}
}
---------------------------------------------------------------------------------------------------------------------------------
8.service层创建empl和ex文件,分别存放接口的实现类和实现层的异常
9.在ex文件中,创建两个异常类:用户已存在异常和插入时异常。还有一个基类异常
package com.cy.store.service.ex;
public class ServiceException extends RuntimeException{
public ServiceException() {
super();
}
public ServiceException(String message) {
super(message);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(Throwable cause) {
super(cause);
}
protected ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.cy.store.service.ex;
public class UsernameDuplicateException extends ServiceException {
public UsernameDuplicateException() {
super();
}
public UsernameDuplicateException(String message) {
super(message);
}
public UsernameDuplicateException(String message, Throwable cause) {
super(message, cause);
}
public UsernameDuplicateException(Throwable cause) {
super(cause);
}
protected UsernameDuplicateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.cy.store.service.ex;
public class InsertException extends ServiceException{
public InsertException() {
super();
}
public InsertException(String message) {
super(message);
}
public InsertException(String message, Throwable cause) {
super(message, cause);
}
public InsertException(Throwable cause) {
super(cause);
}
protected InsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
10.在service层创建IUserService接口
package com.cy.store.service;
import com.cy.store.entity.User;
import org.springframework.stereotype.Service;
public interface IUserService {
void reg(User user);
}
11.在empl创建UserMapperImpl
package com.cy.store.service.empl;
import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicateException;
import org.apache.tomcat.util.digester.Digester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public void reg(User user) {
//判断用户名是否被注册过
String username = user.getUsername();
User result = userMapper.findByUsername(username);
if(result != null){
throw new UsernameDuplicateException("用户名被占用");
}
//老密码
String oldpassword = user.getPassword();
//盐值
String salt = UUID.randomUUID().toString().toUpperCase(Locale.ROOT);
//加密老密码
String md5Password = getMd5Password(oldpassword,salt);
user.setPassword(md5Password);
//补全盐值
user.setSalt(salt);
//是否删除
user.setIsDelete(0);
//补全四个日志
user.setCreatedUser(user.getUsername());
user.setModifiedUser(user.getUsername());
Date date = new Date();
user.setCreatedTime(date);
user.setModifiedTime(date);
//执行注册
Integer rows = userMapper.insert(user);
if(rows != 1){
throw new InsertException("插入过程中,产生未知异常");
}
}
//定义一个md5算法加密
public String getMd5Password(String password , String salt){
//三次加密
for(int i = 0;i < 3;i++){
password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes(StandardCharsets.UTF_8)).toUpperCase(Locale.ROOT);
}
return password;
}
}
12.创建service层测试类
package com.cy.store.service;
import com.cy.store.entity.User;
import com.cy.store.service.ex.ServiceException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTests {
@Autowired
private IUserService iUserService;
@Test
public void reg(){
try {
User user = new User();
user.setPassword("111");
user.setUsername("999");
System.out.println(user);
iUserService.reg(user);
}catch (ServiceException e){
System.out.println(e.getClass().getSimpleName());
System.out.println(e.getMessage());
}
}
}
-------------------------------------------------------------------------------------------------------------------------
13.util包,存放数据包装工具类
package com.cy.store.util; import java.io.Serializable; public class JsonResultimplements Serializable { //状态码 private Integer state; //描述信息 private String message; //数据 private E data; public JsonResult() { } public JsonResult(Integer state) { this.state = state; } public JsonResult(Throwable e) { this.message = e.getMessage(); } public JsonResult(Integer state, E data) { this.state = state; this.data = data; } public JsonResult(Integer state, String message, E data) { this.state = state; this.message = message; this.data = data; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public E getData() { return data; } public void setData(E data) { this.data = data; } }
14.controller层的basecontroller类,负责异常统一处理
package com.cy.store.controller;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.ServiceException;
import com.cy.store.service.ex.UsernameDuplicateException;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
public class BaseController {
//操作成功状态码
public static final int ok = 200;
//该请求处理方法,这个方法的返回值就是传递给前端的数据。
@ExceptionHandler(ServiceException.class)
public JsonResult handlerException(Throwable e){
JsonResult result = new JsonResult();
if(e instanceof UsernameDuplicateException){
result.setState(4000);
result.setMessage(e.getMessage());
}else if(e instanceof InsertException){
result.setState(5000);
result.setMessage(e.getMessage());
}
return result;
}
}
15.创建controller层UserController
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
public class UserController extends BaseController{
@Autowired
private IUserService iUserService;
@RequestMapping(value = "/reg")
public JsonResult reg(User user) {
iUserService.reg(user);
return new JsonResult(ok);
}
16.注册网页
电脑商城 欢迎访问电脑商城新用户注册
-----------------------------------------------------------------------------------------------------------------------------
1.收获
@ExceptionHandler(ServiceException.class)用来捕获异常,用它可以实现异常统一处理的功能。
代码编译之后,会生成target文件,mapper.xml文件加载进去,mybatis层不能扫描到,要在配置文件里配置。
target-》classes-》mapper-》usermapper.xml



