优品商城-注册登录(User、Member)

该博客介绍了如何在Spring Boot应用中整合FastDFS文件系统,实现用户和会员的注册及登录功能。包括User和Member实体的创建、Mapper接口定义、Service层业务逻辑处理以及Controller层接口实现。同时,使用MD5加密密码,并通过ResponseCode返回状态。测试类展示了文件上传和用户添加的测试用例。
摘要由CSDN通过智能技术生成

1 user注册及登录

1.1 User中id加@TableId(type = IdType.ID_WORKER_STR)

1.2 UserMapper

package com.xzy.um.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xzy.common.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

1.3 测试类

  • 在startup启动类中添加测试类
	@Test
    public void add() {
        User user = new User();
        user.setNickname("张三");
        user.setPassword("12345");
        userMapper.insert(user);
    }
  • fdfs工具类
package com.xzy.common.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class FdfsUtils {
    private FdfsUtils(){}

    /**
     * @param fdsStorageFile fdfs提供的操作类对象
     * @param file 要上传的文件对象
     * @return 文件在fdfs中的全路径
     * @throws FileNotFoundException
     */
    public static String upLoadFile(FastFileStorageClient fdsStorageFile,File file) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(file);
        StorePath storePath = fdsStorageFile.uploadFile(fis, file.length(), FilenameUtils.getExtension(file.getName()), null);
        return storePath.getFullPath();
    }

    public static String upLoadFile(FastFileStorageClient fdsStorageFile, InputStream ins, String fileName,Long fileSize) throws FileNotFoundException {
        StorePath storePath = fdsStorageFile.uploadFile(ins,fileSize,FilenameUtils.getExtension(fileName), null);
        return storePath.getFullPath();
    }
}

  • 测试上传文件(头像)
package com.xzy.um;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xzy.Application;
import com.xzy.common.util.FdfsUtils;
import org.apache.commons.io.FilenameUtils;
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;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class FdfsTest {
    @Autowired
    private FastFileStorageClient fdfsStorageFile;

    @Test
    public void testUploadFile() throws FileNotFoundException {
        File file = new File("e:/dj.jpg");
        FileInputStream fis = new FileInputStream(file);
        StorePath storePath = fdfsStorageFile.uploadFile(fis, file.length(), FilenameUtils.getExtension(file.getName()),null);
        System.out.println(storePath.getFullPath());
    }

    @Test
    public void testUpload() throws FileNotFoundException {
        File file = new File("e:/dj.jpg");
        String s = FdfsUtils.upLoadFile(fdfsStorageFile, file);
        System.out.println(s);
    }
}

1.4 UserService

package com.xzy.um.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xzy.common.entity.User;
import com.xzy.common.util.FdfsUtils;
import com.xzy.um.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Transient;
import java.io.IOException;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> listAll() {
        return userMapper.selectList(null);
    }

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 添加用户 1. 把头像上传到fdfs中,返回访问路径   2.把用户名和密码和访问路径添加到数据库
     * @param nickname
     * @param password
     * @return
     */
    @Transient
    public int add(String nickname, String password, MultipartFile avatarFile) throws IOException {
        //给fdfs中上传文件
        String fdfsFullPath = FdfsUtils.upLoadFile(fastFileStorageClient, avatarFile.getInputStream(), avatarFile.getOriginalFilename(), avatarFile.getSize());
        System.out.println(fdfsFullPath);
        User user = new User();
        user.setNickname(nickname);
        user.setPassword(password);
        user.setAvatar(fdfsFullPath);
        return userMapper.insert(user);
    }

    /**
     * 查询用户
     * @param nickname 用户名
     * @param password 加密后的密码
     * @return
     */
    public User findBy(String nickname,String password){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nickname",nickname);
        queryWrapper.eq("password",password);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}

1.5 common中entity中加vo写Response和ResponseCode

package com.xzy.common.entity.vo;

import lombok.Data;

@Data
public class Response {
    private Integer code;
    private String msg;
    private Object data;
    public Response code(Integer code) {
        this.code = code;
        return this;
    }
    public Response msg(String msg) {
        this.msg = msg;
        return this;
    }
    public Response data(Object data) {
        this.data = data;
        return this;
    }
}

package com.xzy.common.entity.vo;

public interface ResponseCode {
    Integer SUCCESS = 666;
    Integer ERROR = 888;
}

1.6 UserController

  • 用md5加密密码 DigestUtils.md5DigestAsHex(password.getBytes());
package com.xzy.um.controller;

import com.xzy.common.entity.User;
import com.xzy.common.entity.vo.Response;
import com.xzy.common.entity.vo.ResponseCode;
import com.xzy.common.util.JwtUtils;
import com.xzy.um.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/all")
    public List<User> findAll() {
        return userService.listAll();
    }

    @PostMapping("/regist")
    public Response regist(String nickname, String password, MultipartFile avatarFile) throws Exception {
        //把密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        int row = userService.add(nickname, md5Password, avatarFile);
        Response response = new Response();
        if (row > 0) {
            //注册成功
            response.code(ResponseCode.SUCCESS).msg("注册成功");
        } else {
            //注册失败
            //response.code(ResponseCode.ERROR).msg("注册失败");
            throw new Exception("注册失败");
        }

        return response;
    }

    @PostMapping("/login")
    public Response login(String nickname, String password, HttpServletResponse httpServletResponse){
        //对密码进行加密
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = userService.findBy(nickname, md5password);
        Response resp = new Response();
        if(user == null){
            //登录失败
            resp.code(ResponseCode.ERROR).msg("登录失败");
        }else {
            //登录成功
            resp.code(ResponseCode.SUCCESS).msg("登录成功");
            //给响应头添加Token令牌
            httpServletResponse.setHeader("token", JwtUtils.getJwtToken(user.getId()));
        }
        return resp;
    }
}

1.7 测试

在这里插入图片描述
在这里插入图片描述

2 member注册

2.1 MemberMapper

package com.xzy.um.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xzy.common.entity.Member;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface MemberMapper extends BaseMapper<Member> {
}

2.2 MemberService

package com.xzy.um.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xzy.common.entity.Member;
import com.xzy.common.util.FdfsUtils;
import com.xzy.um.dao.MemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class MemberService {
    @Autowired
    private MemberMapper memberMapper;

    public List<Member> listAll(){
        return memberMapper.selectList(null);
    }

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public int add(String nickname, String password,String phone, MultipartFile avatarFile) throws IOException {
        //给fdfs上传文件
        String fdfsFullPath = FdfsUtils.upLoadFile(fastFileStorageClient, avatarFile.getInputStream(), avatarFile.getOriginalFilename(), avatarFile.getSize());
        Member member = new Member();
        member.setNickname(nickname);
        member.setPassword(password);
        member.setAvatar(fdfsFullPath);
        member.setPhone(phone);
        Date date = new Date();
        member.setGmtCreate(date);
        member.setGmtModify(date);
        return memberMapper.insert(member);
    }

    public Member findBy(String nickname, String password){
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nickname",nickname);
        queryWrapper.eq("password",password);
        Member member = memberMapper.selectOne(queryWrapper);
        return member;
    }
}

2.3 MemberController

package com.xzy.um.controller;

import com.xzy.common.entity.Member;
import com.xzy.common.entity.vo.Response;
import com.xzy.common.entity.vo.ResponseCode;
import com.xzy.common.util.JwtUtils;
import com.xzy.um.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @GetMapping("/all")
    public List<Member> findAll() {
        return memberService.listAll();
    }

    /**
     * 用户注册
     * @param nickname 用户昵称
     * @param password 登录密码
     * @param phone 用户手机号
     * @param avatarFile 用户头像信息
     * @return
     * @throws Exception
     */
    @PostMapping("/regist")
    public Response regist(String nickname, String password, String phone, MultipartFile avatarFile) throws Exception {
        //把密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        int row = memberService.add(nickname, md5Password, phone, avatarFile);
        Response response = new Response();
        if (row > 0) {
            //注册成功
            response.code(ResponseCode.SUCCESS).msg("注册成功");
        } else {
            //注册失败
            //response.code(ResponseCode.ERROR).msg("注册失败");
            throw new Exception("注册失败");
        }

        return response;
    }

    /**
     * 用户登录
     * @param nickname 用户昵称
     * @param password 用户密码
     * @param httpServletResponse Response请求
     * @return
     */
    @PostMapping("/login")
    public Response login(String nickname, String password, HttpServletResponse httpServletResponse) {
        //对密码进行加密
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
        Member member = memberService.findBy(nickname, md5password);
        Response resp = new Response();
        if (member == null) {
            //登录失败
            resp.code(ResponseCode.ERROR).msg("登录失败");
        } else {
            //登录成功
            resp.code(ResponseCode.SUCCESS).msg("登录成功");
            //给响应头添加Token令牌
            httpServletResponse.setHeader("token", JwtUtils.getJwtToken(member.getId()));
        }
        return resp;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值