栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot电脑商城1期

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot电脑商城1期

这一期是实现用户注册功能。

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 JsonResult  implements 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.注册网页



	
		
		
		
		
		
		电脑商城
		
		
		
		
		
		
		
		
			
			欢迎访问电脑商城
		
		
		
			
			
				

新用户注册

已经有账号?登录

品质保障

私人订制

学生特供

专属特权

  • 买家帮助

  • 新手指南
  • 服务保障
  • 常见问题
  • 商家帮助

  • 商家入驻
  • 商家后台
  • 关于我们

  • 关于圆心
  • 联系我们

电脑商城客户端

Copyright © 2022 dnsc.cn All Rights Reserved 京ICP备08963888号-45 圆心科技集团有限公司 版权所有

-----------------------------------------------------------------------------------------------------------------------------

1.收获

@ExceptionHandler(ServiceException.class)用来捕获异常,用它可以实现异常统一处理的功能。

代码编译之后,会生成target文件,mapper.xml文件加载进去,mybatis层不能扫描到,要在配置文件里配置。

target-》classes-》mapper-》usermapper.xml

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/831374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号