前后端分离,springboot与前端数据交互

7 篇文章 0 订阅
4 篇文章 0 订阅
==由于之前工作数据封装比较乱,所以才写的这边文章。
本意为记录一下以后便于查找。本文章只有后端部分。==

1.创建返回实体类

package com.boke.response;

/**
 * @author Administrator
 */
public class RepsonseData<T> {
    /**
     * 返回的状态码
     */
    private int code;
    /**
     * 返回的信息
     */
    private String message;
    /**
     * 返回的实体类或者列表等一些信息
     */
    private T data;
    /**
     * 当返回的是列表时,用来返回总数的
     */
    private long total;

    public RepsonseData() {
    }

    public RepsonseData(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public RepsonseData(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public RepsonseData(int code, String message, T data, long total) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.total = total;
    }

    public int getCode() {
        return code;
    }

    public RepsonseData setCode(int code) {
        this.code = code;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public RepsonseData setMessage(String message) {
        this.message = message;
        return this;
    }

    public T getData() {
        return data;
    }

    public RepsonseData setData(T data) {
        this.data = data;
        return this;
    }

    public long getTotal() {
        return total;
    }

    public RepsonseData setTotal(long total) {
        this.total = total;
        return this;
    }
}

2.创建一个BaseController类,之后每一个Controller都继承这个类

package com.boke.response;


import com.alibaba.fastjson.JSONObject;

/**
 * @author Administrator
 */
public class BaseController<T>{
    public static final int ERROR_CODE = -1;
    public static final String ERROR_MESSAGE = "服务器异常";
    public static final int SUCCESS_CODE = 1;
    public static final String SUCCESS_MESSAGE = "ok";
    /**
     * 当新增,修改,删除的时候只需要返回成功即可的直接在接口中return SUCCESS;即可
     */
    public static final String SUCCESS;

    static {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",SUCCESS_CODE);
        jsonObject.put("message",SUCCESS_MESSAGE);
        SUCCESS = jsonObject.toJSONString();

    }

    /**
     * 返回带数据的,非列表
     * @param data
     * @return
     */
    public  RepsonseData data(Object data){
        return new RepsonseData(SUCCESS_CODE,SUCCESS_MESSAGE,data);
    }

    /**
     * 返回带数据的,列表
     * @param data
     * @param total
     * @return
     */
    public  RepsonseData data( Object data, long total){
        return new RepsonseData(SUCCESS_CODE,SUCCESS_MESSAGE,data,total);
    }
}

3.接口api中返回示例

/**
 * @author Administrator
 */
@RestController
@Slf4j
public class TestController extends BaseController {
	@GetMapping("/test")
    public String get(){
        return SUCCESS;
    }
	@PostMapping("/list")
    public Object list(@RequestBody RoleVo roleVo) throws ResultException {
        PageInfo<Role> pageInfo = roleService.roleList(roleVo);
        return data(pageInfo.getList(),pageInfo.getTotal());
    }

}

4.定义全局异常类,同时自定义一个异常类,用来返回错误请求,又不是代码异常的信息

package com.boke.exception;

import com.boke.response.BaseController;
import lombok.Data;

/**
 * 定义异常类,用来返回一些接口自定义的异常,取代以前的在controller中自定义返回
 * @author Administrator
 */
@Data
public class ResultException extends Exception{
    private int code = BaseController.ERROR_CODE;
    private String message;

    public ResultException(String message) {
        this.message = message;
    }
}

package com.boke.exception;

import com.alibaba.fastjson.JSONObject;
import com.boke.response.BaseController;
import com.boke.tools.SendMessageToWeb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 返回前端的全局异常处理
 * @author Administrator
 */
@ControllerAdvice
public class GlobalException {
    /**
     * 用来封装自定义异常,返回前端信息
     */
    private static JSONObject jsonObject = new JSONObject();
    /**
     * 用来返回程序异常信息
     */
    private static final String EXCEPTION_STRING;
    static {
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("code", BaseController.ERROR_CODE);
        jsonObject2.put("message", BaseController.ERROR_MESSAGE);
        EXCEPTION_STRING = jsonObject2.toJSONString();
    }

    /**
     * 处理Exception异常
     * */
    @ExceptionHandler(value = Exception.class)
    public void badRequestParameterException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        jsonObject.clear();
        //判断异常类型是否是我们自己抛出去的异常
        if (e instanceof ResultException){
            jsonObject.put("code",((ResultException) e).getCode());
            jsonObject.put("message",e.getMessage());
            SendMessageToWeb.returnJson(response,jsonObject.toJSONString());
            return;
        }

        SendMessageToWeb.returnJson(response,EXCEPTION_STRING);
        e.printStackTrace();
    }

}

5.自定义异常的使用

package com.boke.login.impl;

import com.boke.exception.ResultException;
import com.boke.login.Login;
import com.boke.login.LoginMapper;
import com.boke.login.LoginService;
import com.boke.login.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Login loginService(LoginVo loginVo) throws ResultException {
        //字段校验
        checkLoginField(loginVo);
        Login login= loginMapper.getUserByUserName(loginVo.getUsername());
        if (login == null){
            throw new ResultException("没有该用户");
        }
        if (!loginVo.getPassword().equals(login.getPassword())){
            throw new ResultException("密码错误");
        }
       return login;
    }

    /**
     * 登录操作字段验证
     * @param loginVo
     */
    private void checkLoginField(LoginVo loginVo) throws ResultException {
        if (StringUtils.isBlank(loginVo.getUsername())){
            throw new ResultException("用户名不能为空");
        }
        if (StringUtils.isBlank(loginVo.getPassword())){
            throw new ResultException("密码不能为空");
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值