IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> SpringBoot实现电商管理后台登录用户管理功能 -> 正文阅读

[网络协议]SpringBoot实现电商管理后台登录用户管理功能

一.电商管理后台 API 接口

1.1API V1 接口说明

  • 接口基准地址:http://127.0.0.1:8888/api/private/v1/
  • 服务端已开启 CORS 跨域支持
  • API V1 认证统一使用 Token 认证
  • 需要授权的 API ,必须在请求头中使用 Authorization 字段提供 token 令牌
  • 使用 HTTP Status Code 标识状态
  • 数据返回格式统一使用 JSON

1.2 支持的请求方法

  • GET(SELECT):从服务器取出资源(一项或多项)。
  • POST(CREATE):在服务器新建一个资源。
  • PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
  • PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
  • DELETE(DELETE):从服务器删除资源。
  • HEAD:获取资源的元数据。
  • OPTIONS:获取信息,关于资源的哪些属性是客户端可以改变的。

1.3 通用返回状态说明

状态码含义说明
200OK请求成功
201CREATED创建成功
204DELETED删除成功
400BAD REQUEST请求的地址不存在或者包含不支持的参数
401UNAUTHORIZED未授权
403FORBIDDEN被禁止访问
404NOT FOUND请求的资源不存在
422Unprocesable entity[POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误
500INTERNAL SERVER ERROR内部错误

二.登录

2.1登录验证接口

  • 请求路径:login
  • 请求方法:post
  • 请求参数
参数名参数说明备注
username用户名不能为空
password密码不能为空
  • 响应参数
参数名参数说明备注
id用户 ID
rid用户角色 ID
username用户名
mobile手机号
email邮箱
token令牌基于 jwt 的令牌
  • 响应数据
{
    "data": {
        "id": 500,
        "rid": 0,
        "username": "admin",
        "mobile": "123",
        "email": "123@qq.com",
        "token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE1MTI1NDQyOTksImV4cCI6MTUxMjYzMDY5OX0.eGrsrvwHm-tPsO9r_pxHIQ5i5L1kX9RX444uwnRGaIM"
    },
    "meta": {
        "msg": "登录成功",
        "status": 200
    }
}

后端实现

数据返回实体类封装

Meta.java

package com.vueshop.manager.controller.http.response.base;

import lombok.Data;

/**
 * 数据返回状态码
 * @author yxm 
 * @date 2021/11/23 10:03
 */
@Data
public class Meta {
    
    private String msg;
    private Integer status;
}

HttpResponse.java

package com.vueshop.manager.controller.http.response.base;

import lombok.Data;

/**
 * 数据返回统一实体类
 * @author yxm
 * @date 2021/11/23
 */
@Data
public class HttpResponse<T> {

    private T data;

    private Meta meta;

    public HttpResponse() {
    }

    public HttpResponse(Meta meta) {
        this.meta = meta;
    }
}

用户请求实体类和用户响应实体类

UserInfoResponse.java

package com.vueshop.manager.controller.http.response;

import lombok.Data;

/**
 * 用户响应实体类
 * @author yxm
 * @date 2021/11/23 10:10
 */
@Data
public class UserInfoResponse {

    private Long id;

    private Long rid;

    private String username;

    private String mobile;

    private String email;

    private String token;

    private String password;

    private String createtime;

    private String updatetime;
}

UserInfoRequest.java

package com.vueshop.manager.controller.http.request;

import lombok.Data;

/**
 * 用户请求实体类
 * @author yxm
 * @date 2021/11/23 10:23
 */
@Data
public class UserInfoRequest {

    private Long id;

    private String username;

    private String password;

    private Integer status;

    private String email;

    private String mobile;

    private Integer rid;
}

LoginController.java

@RestController
@RequestMapping("api/private/v1/")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    public HttpResponse<UserInfoResponse> login(HttpServletRequest request,
                                                @RequestBody UserInfoRequest userInfoRequest){
        HttpResponse<UserInfoResponse> httpResponse=new HttpResponse<>(new Meta());

        try {
            UserInfoResponse userInfoResponse = loginService.queryUserInfo(userInfoRequest);
            if (userInfoResponse == null || !userInfoResponse.getPassword().equals(userInfoRequest.getPassword())) {
                httpResponse.getMeta().setMsg("登录失败");
                httpResponse.getMeta().setStatus(400);
                return httpResponse;
            }
            httpResponse.setData(userInfoResponse);
            httpResponse.getMeta().setMsg("登录成功");
            httpResponse.getMeta().setStatus(200);
        } catch (Exception e) {
            log.error(e.getMessage());
            httpResponse.getMeta().setMsg("登录失败");
            httpResponse.getMeta().setStatus(400);
        }
        return  httpResponse;
    }

LoginServiceImpl.java

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private Map<String, AuthInfoDto> redisCache;

    @Autowired
    private MenuInfoDao menuInfoDao;

    @Override
    public UserInfoResponse queryUserInfo(UserInfoRequest userInfoRequest) {

        UserInfo userInfo = userInfoDao.queryUserInfo(userInfoRequest.getUsername());
        if(userInfo==null){
            return null;
        }

        List<MenuInfo> menuInfos = menuInfoDao.queryMenuInfoByRoleId(userInfo.getRid());

        UserInfoResponse userInfoResponse=new UserInfoResponse();
        BeanUtils.copyProperties(userInfo,userInfoResponse);

        String token= UUID.randomUUID().toString().replace("-","");
        userInfoResponse.setToken(token);
        AuthInfoDto authInfoDto=new AuthInfoDto();
        authInfoDto.setUserInfo(userInfo);
        authInfoDto.setMenuInfos(menuInfos);

        redisCache.put(token,authInfoDto);

        return userInfoResponse;
    }
}

UserInfoDaoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vueshop.manager.dao.mapper.UserInfoDao">

    <resultMap id="UserInfoMap" type="com.vueshop.manager.dao.model.UserInfo">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="rid" property="rid" jdbcType="BIGINT"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="mobile" property="mobile" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR"/>
        <result column="token" property="token" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="status" property="status" jdbcType="TINYINT"/>
        <result column="role_name" property="roleName" jdbcType="VARCHAR"/>
        <result column="createtime" property="createtime" jdbcType="TIMESTAMP"/>
        <result column="updatetime" property="updatetime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="allColumn">
        id,
        rid,
        username,
        mobile,
        email,
        token,
        password,
        status,
        createtime,
        updatetime
    </sql>

    <select id="queryUserInfo" resultMap="UserInfoMap">
        select <include refid="allColumn"/>
        from user_info
        where username= #{username}
        AND status=1
    </select>
</mapper>

MenuInfoDaoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vueshop.manager.dao.mapper.MenuInfoDao">

    <resultMap id="MenuInfoMap" type="com.vueshop.manager.dao.model.MenuInfo">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="auth_name" property="authName" jdbcType="VARCHAR"/>
        <result column="path" property="path" jdbcType="VARCHAR"/>
        <result column="pid" property="pid" jdbcType="BIGINT"/>
        <result column="status" property="status" jdbcType="TINYINT"/>
        <result column="display" property="display" jdbcType="TINYINT"/>
        <result column="level" property="level" jdbcType="TINYINT"/>
        <result column="createtime" property="createtime" jdbcType="TIMESTAMP"/>
        <result column="updatetime" property="updatetime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="allColumn">
        id,
        auth_name,
        path,
        pid,
        status,
        display,
        level,
        createtime,
        updatetime
    </sql>


    <select id="queryMenuInfoByRoleId" resultMap="MenuInfoMap" >
        SELECT
            um.id,
            um.auth_name,
            um.path,
            um.pid,
            um.status,
            um.display,
            um.level,
            um.createtime,
            um.updatetime
        FROM user_menus um
        RIGHT JOIN user_role_menu urm ON um.id = urm.menu_id
        WHERE STATUS = 1
        AND urm.role_id =#{roleId}
        ORDER BY LEVEL ASC

    </select>
</mapper>

拦截器
AuthInterceptor.java

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {


	@Autowired
	protected Map<String, AuthInfoDto> redisCache;

	private static final List<String> menuWhiteList = Arrays.asList("home", "menus", "login");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		AuthInfoDto authInfoDto = loginAuthorizationCheck(request);
		if (authInfoDto.isNotAuth()) {
			HttpResponse httpResponse = new HttpResponse();
			Meta meta = new Meta();
			meta.setMsg(authInfoDto.getErrMsg());
			meta.setStatus(400);
			httpResponse.setMeta(meta);
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(JSON.toJSONString(httpResponse));
			return false;
		}
		return true;
	}


	public AuthInfoDto loginAuthorizationCheck(HttpServletRequest request) {
		AuthInfoDto authInfoDto = redisCache.get(request.getHeader("Authorization"));
		if (authInfoDto == null) {
			authInfoDto = new AuthInfoDto();
			authInfoDto.setErrMsg("未登录");
			authInfoDto.setNotAuth(true);
			return authInfoDto;
		}
		boolean isAccept = false;
		String requestURI = request.getRequestURI();
		for (MenuInfo menuInfo : authInfoDto.getMenuInfos()) {
			if (menuInfo.getPath() == null) {
				continue;
			}
			if (requestURI.contains(menuInfo.getPath())) {
				isAccept = true;
				break;
			}
		}
		for (String uri : menuWhiteList) {
			if (requestURI.contains(uri)) {
				isAccept = true;
				break;
			}
		}

		if (!isAccept) {
			authInfoDto.setErrMsg("没有权限访问该路径");
			authInfoDto.setNotAuth(true);
		}
		return authInfoDto;
	}

}

InterceptorConfig.java

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

	@Autowired
	AuthInterceptor authInterceptor;


	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(authInterceptor)
				.addPathPatterns("/api/private/v1/**")
				.excludePathPatterns("/api/private/v1/login")
				.excludePathPatterns("/api/private/v1/historyBrief/**")
				.excludePathPatterns("/api/private/v1/historyBriefEvent/**");
	}
}

三.用户管理

3.1用户数据列表

  • 请求路径:users
  • 请求方法:get
  • 请求参数
参数名参数说明备注
query查询参数可以为空
pagenum当前页码不能为空
pagesize每页显示条数不能为空
  • 响应参数
参数名参数说明备注
totalpage总记录数
pagenum当前页码
users用户数据集合
  • 响应数据
{
    "data": {
        "totalpage": 5,
        "pagenum": 4,
        "users": [
            {
                "id": 25,
                "username": "tige117",
                "mobile": "18616358651",
                "type": 1,
                "email": "tige112@163.com",
                "create_time": "2017-11-09T20:36:26.000Z",
                "mg_state": true, // 当前用户的状态
                "role_name": "炒鸡管理员"
            }
        ]
    },
    "meta": {
        "msg": "获取成功",
        "status": 200
    }
}

后端实现

分页实体类 PageResponse.java

@Data
public class PageResponse {
    
    private Integer total;
    
    private Integer pagenum;
}

用户查询响应实体类继承分页实体类UserInfoQueryResponse.java

@Data
public class UserInfoQueryResponse extends PageResponse {

   private List<UserInfo> users;
}

用户分页查询封装实体类PageRequest.java

@Data
public class PageRequest<T> {

    private Integer pagenum;
    private Integer pagesize;
    private Integer pagestart;
    private T query;

    public PageRequest(Integer pagenum, Integer pagesize) {
        this.pagenum = pagenum;
        this.pagesize = pagesize;
        if(pagenum != null && pagesize != null){
            this.pagestart = (pagenum - 1) * pagesize;
        }
    }

    public PageRequest() {
    }

}

@RestController
@RequestMapping("api/private/v1/")
@Slf4j
public class UsersController {

    @Autowired
    private UsersService usersService;

    @GetMapping("users")
    public HttpResponse<UserInfoQueryResponse> queryUserPage(HttpServletRequest request) {
        HttpResponse<UserInfoQueryResponse> httpResponse = new HttpResponse<>(new Meta());

        String pagenum = request.getParameter("pagenum");
        String pagesize = request.getParameter("pagesize");
        String query = request.getParameter("query");
        PageRequest<UserInfoQueryRequest> pageRequest = new PageRequest(Integer.parseInt(pagenum),
                Integer.parseInt(pagesize));
        UserInfoQueryRequest userInfoQueryRequest = new UserInfoQueryRequest();
        userInfoQueryRequest.setUsername(query);
        pageRequest.setQuery(userInfoQueryRequest);
        UserInfoQueryResponse userInfoPageResponse = usersService.queryUserPage(pageRequest);

        httpResponse.setData(userInfoPageResponse);
        httpResponse.getMeta().setMsg("获取菜单列表成功");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }
}

UsersServiceImpl.java

@Service
@Slf4j
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public UserInfoQueryResponse queryUserPage(PageRequest<UserInfoQueryRequest> pageRequest) {
        UserInfoQueryResponse res = new UserInfoQueryResponse();
        List<UserInfo> userInfos = userInfoDao.queryUserPage(pageRequest.getQuery(), pageRequest.getPagestart(), pageRequest.getPagesize());
        Integer count = userInfoDao.queryUserPageCount(pageRequest.getQuery());
        for (UserInfo userInfo : userInfos) {
            userInfo.setMg_state(userInfo.getStatus() == 1 ? true : false);
        }
        res.setTotal(count);
        res.setPagenum(pageRequest.getPagenum());
        res.setUsers(userInfos);
        return res;
    }
 }

UserInfoDaoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vueshop.manager.dao.mapper.UserInfoDao">
 <resultMap id="UserInfoMap" type="com.vueshop.manager.dao.model.UserInfo">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="rid" property="rid" jdbcType="BIGINT"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="mobile" property="mobile" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR"/>
        <result column="token" property="token" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="status" property="status" jdbcType="TINYINT"/>
        <result column="role_name" property="roleName" jdbcType="VARCHAR"/>
        <result column="createtime" property="createtime" jdbcType="TIMESTAMP"/>
        <result column="updatetime" property="updatetime" jdbcType="TIMESTAMP"/>
    </resultMap>
    
    <sql id="allColumn">
       id,
       rid,
       username,
       mobile,
       email,
       token,
       password,
       status,
       createtime,
       updatetime
    </sql>
    
     <select id="queryUserPage" resultMap="UserInfoMap">
        SELECT
        ur.role_name,
        ui.id,
        ui.rid,
        ui.username,
        ui.mobile,
        ui.email,
        ui.token,
        ui.password,
        ui.status,
        ui.createtime,
        ui.updatetime
        FROM user_info ui
        LEFT JOIN user_role ur
        ON ui.rid = ur.id
        <where>
            <if test=" query.username != null and query.username != ''">
                AND ui.username =#{query.username}
            </if>
        </where>
        ORDER BY ui.id ASC
        LIMIT #{pageNo} , #{pageSize}
    </select>
</mapper>

3.2. 添加用户

  • 请求路径:users
  • 请求方法:post
  • 请求参数
参数名参数说明备注
username用户名称不能为空
password用户密码不能为空
email邮箱可以为空
mobile手机号可以为空
  • 响应参数
参数名参数说明备注
id用户 ID
rid用户角色 ID
username用户名
mobile手机号
email邮箱
  • 响应数据
{
    "data": {
        "id": 28,
        "username": "tige1200",
        "mobile": "test",
        "type": 1,
        "openid": "",
        "email": "test@test.com",
        "create_time": "2017-11-10T03:47:13.533Z",
        "modify_time": null,
        "is_delete": false,
        "is_active": false
    },
    "meta": {
        "msg": "用户创建成功",
        "status": 201
    }
}

后端实现

用户添加实体类UserInfoRequest.java

@Data
public class UserInfoRequest {

    private Long id;

    private String username;

    private String password;

    private Integer status;

    private String email;

    private String mobile;

    private Integer rid;
}

UsersController.java

    @PostMapping("users")
    public HttpResponse<UserInfoResponse> addUser(HttpServletRequest request,
                                                  @RequestBody UserInfoRequest userInfoRequest) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        UserInfoResponse userInfoResponse = usersService.insertUser(userInfoRequest);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("用户创建成功");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("用户创建失败");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

   @Override
    public UserInfoResponse insertUser(UserInfoRequest userInfoRequest) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        try {
            userInfoRequest.setStatus(1);
            userInfoDao.insertUserInfo(userInfoRequest);
        } catch (Exception e) {
            log.error("添加失败", e.getMessage());
            return null;
        }
        BeanUtils.copyProperties(userInfoRequest, userInfoResponse);
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

    <insert id="insertUserInfo" parameterType="com.vueshop.manager.controller.http.request.UserInfoRequest">
       INSERT INTO user_info (rid,username,mobile,email,password,status,createtime,updatetime)
       VALUES (#{userInfo.rid},#{userInfo.username},#{userInfo.mobile},#{userInfo.email},#{userInfo.password},#{userInfo.status},NOW(),NOW())
    </insert>

3.3. 修改用户状态

  • 请求路径:users/:uId/state/:type
  • 请求方法:put
  • 请求参数
参数名参数说明备注
uId用户 ID不能为空携带在url中
type用户状态不能为空携带在url中,值为 true 或者 false
  • 响应数据
{
  "data": {
    "id": 566,
    "rid": 30,
    "username": "admin",
    "mobile": "123456",
    "email": "bb@itcast.com",
    "mg_state": 0
  },
  "meta": {
    "msg": "设置状态成功",
    "status": 200
  }
}

后端实现

UsersController.java

    @PutMapping("users/{id}/state/{type}")
    public HttpResponse<UserInfoResponse> updateUserStateById(HttpServletRequest request, @PathVariable long id,
                                                              @PathVariable boolean type) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        UserInfoRequest userInfoRequest = new UserInfoRequest();
        userInfoRequest.setId(id);
        userInfoRequest.setStatus(type ? 1 : 0);
        UserInfoResponse userInfoResponse = usersService.updateUserInfoById(userInfoRequest);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("设置失败");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("设置成功");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

    @Override
    public UserInfoResponse updateUserInfoById(UserInfoRequest userInfoRequest) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        try {
            userInfoDao.updateUserInfo(userInfoRequest);
        } catch (Exception e) {
            log.error("更新失败", e.getMessage());
            return null;
        }
        BeanUtils.copyProperties(userInfoRequest, userInfoResponse);
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

  <update id="updateUserInfo" parameterType="com.vueshop.manager.controller.http.request.UserInfoRequest">
        UPDATE user_info
        <set>
            <if test=" userInfo.rid != null">
                rid =#{userInfo.rid},
            </if>
            <if test=" userInfo.mobile != null and userInfo.mobile != ''">
                mobile =#{userInfo.mobile},
            </if>
            <if test=" userInfo.email != null and userInfo.email != ''">
                email =#{userInfo.email},
            </if>
            <if test=" userInfo.password != null and userInfo.password != ''">
                password =#{userInfo.password},
            </if>
            <if test=" userInfo.status != null">
                status =#{userInfo.status},
            </if>
            updatetime = now()
        </set>
        WHERE id =#{userInfo.id}
    </update>

3.4. 根据 ID 查询用户信息

  • 请求路径:users/:id
  • 请求方法:get
  • 请求参数
参数名参数说明备注
id用户 ID不能为空携带在url中
  • 响应参数
参数名参数说明备注
id用户 ID
role_id角色 ID
mobile手机号
email邮箱
  • 响应数据
{
    "data": {
        "id": 503,
        "username": "admin3",
        "role_id": 0,
        "mobile": "00000",
        "email": "new@new.com"
    },
    "meta": {
        "msg": "查询成功",
        "status": 200
    }
}

后端实现

UsersController.java

    @GetMapping("users/{id}")
    @ResponseBody
    public HttpResponse<UserInfoResponse> queryUserById(HttpServletRequest request, @PathVariable long id) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        UserInfoResponse userInfoResponse = usersService.queryUserInfoById(id);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("查询失败");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("查询成功");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

    @Override
    public UserInfoResponse queryUserInfoById(Long id) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = userInfoDao.queryUserInfoById(id);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

    <select id="queryUserInfoById" resultType="com.vueshop.manager.dao.model.UserInfo">
        SELECT
        <include refid="allColumn"/>
        FROM user_info
        WHERE id = #{id}
    </select>

3.5. 编辑用户提交

  • 请求路径:users/:id
  • 请求方法:put
  • 请求参数
参数名参数说明备注
id用户 id不能为空 参数是url参数:id
email邮箱可以为空
mobile手机号可以为空
  • 响应参数
参数名参数说明备注
id用户 ID
role_id角色 ID
mobile手机号
email邮箱
  • 响应数据
/* 200表示成功,500表示失败 */
{
    "data": {
        "id": 503,
        "username": "admin3",
        "role_id": 0,
        "mobile": "111",
        "email": "123@123.com"
    },
    "meta": {
        "msg": "更新成功",
        "status": 200
    }
}

后端实现

UsersController.java

 @PutMapping("users/{id}")
    @ResponseBody
    public HttpResponse<UserInfoResponse> updateUserInfoById(HttpServletRequest request, @PathVariable long id,
                                                             @RequestBody UserInfoRequest userInfoRequest) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        userInfoRequest.setId(id);
		if (userInfoRequest.getStatus() == null) {
			userInfoRequest.setStatus(0);
		}
        UserInfoResponse userInfoResponse = usersService.updateUserInfoById(userInfoRequest);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("更新失败");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("更新成功");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

  @Override
    public UserInfoResponse updateUserInfoById(UserInfoRequest userInfoRequest) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        try {
            userInfoDao.updateUserInfo(userInfoRequest);
        } catch (Exception e) {
            log.error("更新失败", e.getMessage());
            return null;
        }
        BeanUtils.copyProperties(userInfoRequest, userInfoResponse);
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

 <update id="updateUserInfo" parameterType="com.vueshop.manager.controller.http.request.UserInfoRequest">
        UPDATE user_info
        <set>
            <if test=" userInfo.rid != null">
                rid =#{userInfo.rid},
            </if>
            <if test=" userInfo.mobile != null and userInfo.mobile != ''">
                mobile =#{userInfo.mobile},
            </if>
            <if test=" userInfo.email != null and userInfo.email != ''">
                email =#{userInfo.email},
            </if>
            <if test=" userInfo.password != null and userInfo.password != ''">
                password =#{userInfo.password},
            </if>
            <if test=" userInfo.status != null">
                status =#{userInfo.status},
            </if>
            updatetime = now()
        </set>
        WHERE id =#{userInfo.id}
    </update>

3.6. 删除单个用户

  • 请求路径:users/:id
  • 请求方法:delete
  • 请求参数
参数名参数说明备注
id用户 id不能为空参数是url参数:id
  • 响应参数
  • 响应数据
{
    "data": null,
    "meta": {
        "msg": "删除成功",
        "status": 200
    }
}

后端实现

UsersController.java

 @DeleteMapping("users/{id}")
    @ResponseBody
    public HttpResponse<UserInfoResponse> deleteUserById(HttpServletRequest request, @PathVariable long id) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        UserInfoResponse userInfoResponse = usersService.deleteUserById(id);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("删除失败");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("删除成功");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

    @Override
    public UserInfoResponse deleteUserById(Long id) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        try {
            userInfoDao.deleteUserById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return null;
        }
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

    <delete id="deleteUserById" parameterType="java.lang.Long">
       DELETE FROM user_info WHERE id = #{id}
    </delete>

3.7. 分配用户角色

  • 请求路径:users/:id/role
  • 请求方法:put
  • 请求参数
参数名参数说明备注
id用户 ID不能为空参数是url参数:id
rid角色 id不能为空参数body参数
  • 响应参数
参数名参数说明备注
id用户 ID
role_id角色 ID
mobile手机号
email邮箱
  • 响应数据
{
    "data": {
        "id": 508,
        "rid": "30",
        "username": "asdf1",
        "mobile": "123123",
        "email": "adfsa@qq.com"
    },
    "meta": {
        "msg": "设置角色成功",
        "status": 200
    }
}

后端实现

UsersController.java

 @PutMapping("users/{id}/role")
    @ResponseBody
    public HttpResponse<UserInfoResponse> updateUserStateById(HttpServletRequest request, @PathVariable long id, @RequestBody AssignRoleRequest assignRoleRequest) {
        HttpResponse<UserInfoResponse> httpResponse = new HttpResponse<>(new Meta());

        String rid = assignRoleRequest.getRid();
        UserInfoRequest userInfoRequest = new UserInfoRequest();
        userInfoRequest.setId(id);
        userInfoRequest.setRid(Integer.parseInt(rid));
        UserInfoResponse userInfoResponse = usersService.updateUserInfoById(userInfoRequest);

        if (userInfoResponse == null) {
            httpResponse.getMeta().setMsg("设置角色成功");
            httpResponse.getMeta().setStatus(400);
            return httpResponse;
        }

        httpResponse.setData(userInfoResponse);
        httpResponse.getMeta().setMsg("设置角色失败");
        httpResponse.getMeta().setStatus(200);
        return httpResponse;
    }

UsersServiceImpl.java

    @Override
    public UserInfoResponse updateUserInfoById(UserInfoRequest userInfoRequest) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        try {
            userInfoDao.updateUserInfo(userInfoRequest);
        } catch (Exception e) {
            log.error("更新失败", e.getMessage());
            return null;
        }
        BeanUtils.copyProperties(userInfoRequest, userInfoResponse);
        return userInfoResponse;
    }

UserInfoDaoMapper.xml

 <update id="updateUserInfo" parameterType="com.vueshop.manager.controller.http.request.UserInfoRequest">
        UPDATE user_info
        <set>
            <if test=" userInfo.rid != null">
                rid =#{userInfo.rid},
            </if>
            <if test=" userInfo.mobile != null and userInfo.mobile != ''">
                mobile =#{userInfo.mobile},
            </if>
            <if test=" userInfo.email != null and userInfo.email != ''">
                email =#{userInfo.email},
            </if>
            <if test=" userInfo.password != null and userInfo.password != ''">
                password =#{userInfo.password},
            </if>
            <if test=" userInfo.status != null">
                status =#{userInfo.status},
            </if>
            updatetime = now()
        </set>
        WHERE id =#{userInfo.id}
    </update>
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-24 08:19:34  更:2021-11-24 08:20:40 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 7:38:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码