0
点赞
收藏
分享

微信扫一扫

【java工具类】Controller-service流程模板Exception统一处理案例请求前端接口API,返回统一个格式代码,前后端联调的规范化格式操作java代码实现Controller流程


目录


​​前言:​​

​​ShiroSessionManager获取用户id​​

​​Controller,后端对外提供接口示范​​

​​标准的异常处理流程CommonException​​

​​对Exception统一处理返回信息逻辑​​

​​对于前台统一的回复三个参数,状态,状态代码,具体信息------CommonResponse​​

前言:

主要是用于一个新项目,作为一个Demo,给新人讲解,流程是如何进行调用的?,主要来用一个简单的流程来规定下来我们以后所有的REST-Controller的请求逻辑需要怎么样开发!下面也能让新人能够学习到怎么样统一返回我们需要的一个Code码值,这样前端同学能够进行全局进行处理,而不是各个样例进行单独的处理。


ShiroSessionManager获取用户id

主要是通过Shiro管理的Session的管理类,来实现获取请求的用户ID等等信息,一般Session里面有用户id以及用户信息,命名,类别,权限,菜单等等,如果没有接触Shiro,这个工具类可以略过

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class ShiroSessionManager extends DefaultWebSessionManager {

private static final String AUTHORIZATION = "Authorization";

private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

public ShiroSessionManager() {
super();
}

@Override
protected Serializable getSessionId(ServletRequest request,
ServletResponse response) {
String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
// 如果请求头中有 Authorization 则其值为sessionId
if (!StringUtils.isEmpty(id)) {
request.setAttribute(
ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,
id);
request.setAttribute(
ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,
Boolean.TRUE);
return id;
} else {
// 否则按默认规则从cookie取sessionId
return super.getSessionId(request, response);
}
}
}

Controller,后端对外提供接口示范

最为重点的地方:就是怎么全局的返回一个Code码值

这里使用的很好的设计,我们这里目前几十个项目,基本上是使用下面的架构,在controller这一层面上,进行try-catch-返回,通过不同Exception的处理,返回不同的提示,前端同学进行转换就可以的。这里的Exception有很多,我们这里自顶一个APIException,可以在这里返回一个提示信息或者选择样式,然后配置Controller切面的全局的Exception就可以对于全部的合法请求进行流程化的处理,对于新同学也可以按照既有的架构进行开发新的请求和逻辑处理!

全部的参考的rest-controller代码

package com.controller;

import org.apache.avro.data.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.common.api.controller.BaseController;
import com.common.api.service.SessionService;
import com.common.api.service.SessionUser;
import com.controller.common.CommonResponse;
import com.controller.common.CommonResponseBuilder;

/********************************************
* 模块名称: 标准化后端接口发布示范: 功能说明: 开发人员: 开发时间:2020/6/12 14:30 v1.0.0.0 2020/6/12-01
*******************************************/
@RestController
public class TestController extends BaseController {

@Autowired
SessionService sessionService;

@RequestMapping(value = "/getSessionId", method = RequestMethod.POST)
public CommonResponse getSessionId() throws CommonException {
CommonResponse response = CommonResponseBuilder.newSuccessResponse();
try {
Integer sessionId = sessionService.getSessionUserId();
response.setMsg("获取到SessionID:" + sessionId);
} catch (Exception e) {
response = CommonResponseBuilder.newErrorResponse(e);
}
return response;
}

@RequestMapping(value = "/getSessionUser", method = RequestMethod.POST)
public CommonResponse getSessionUser() throws CommonException {
CommonResponse response = CommonResponseBuilder.newSuccessResponse();
try {
SessionUser sessionUser = sessionService.getSessionUser();
response.setMsg("获取到SessionID:" + JSON.toJSONString(sessionUser));
} catch (Exception e) {
response = CommonResponseBuilder.newErrorResponse(e);
}
return response;
}

@RequestMapping(value = "/getSessionUserName", method = { RequestMethod.POST, RequestMethod.GET })
public CommonResponse getSessionUserName() throws CommonException {
CommonResponse response = CommonResponseBuilder.newSuccessResponse();
try {
String sessionUser = sessionService.getSessionUserName();
response.setMsg("获取到SessionID:" + Json.toString(sessionUser));
} catch (Exception e) {
response = CommonResponseBuilder.newErrorResponse(e);
}
return response;
}

@RequestMapping(value = "/test", method = RequestMethod.POST)
public CommonResponse test() throws CommonException {
CommonResponse response = CommonResponseBuilder.newSuccessResponse();
try {
response.setMsg("测试数据---->获取到SessionIDwu");
} catch (Exception e) {
response = CommonResponseBuilder.newErrorResponse(e);
}
return response;
}

}

标准的异常处理流程CommonException

主要是作为自定义的Exception,进行编码和提示信息,返回前端对接。因为系统各种的前置校验可以直接Exception跑出来,然后进行逻辑处理,错误码为 -1,这样的话就可以前端直接禁止类提示。

public class CommonException extends Exception {
private static final long serialVersionUID = 1256016620875694495L;
private int code;
private String msg;

public CommonException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}

public CommonException(String msg) {
super(msg);
this.code = -1;
this.msg = msg;
}

public int getCode() {
return this.code;
}

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

public String getMsg() {
return this.msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

对Exception统一处理返回信息逻辑

通过前面的说明,需要一个类来说明,怎么返回创建,分类的Exception进行前端返回信息。通过下面的这个类,可以分门别类的进行exception处理


package com.controller.common;

import com.controller.CommonException;

public class CommonResponseBuilder {

private static final int RESULT_CODE_SUCCESS = 1;

private static final int RESULT_CODE_PARAM_ERROR = -1;

public static CommonResponse newSuccessResponse() {
CommonResponse apiResponse = new CommonResponse();
apiResponse.setStatus(RESULT_CODE_SUCCESS);
apiResponse.setMsg("success");
return apiResponse;
}

public static CommonResponse newErrorResponse(CommonException e) {
CommonResponse apiResponse = new CommonResponse();
apiResponse.setStatus(e.getCode());
apiResponse.setMsg(e.getMessage());
return apiResponse;
}

public static CommonResponse newErrorResponse(Exception e) {
CommonException ex;
if (e instanceof CommonException) {
ex = (CommonException) e;
} else {
ex = new CommonException(-1, "远端服务调用异常");
}
CommonResponse apiResponse = new CommonResponse();
apiResponse.setStatus(ex.getCode());
apiResponse.setMsg(ex.getMessage());
return apiResponse;
}

public static CommonResponse newParamErrorResponse() {
CommonResponse apiResponse = new CommonResponse();
apiResponse.setStatus(RESULT_CODE_PARAM_ERROR);
apiResponse.setMsg("param error");
return apiResponse;
}

public static CommonResponse newParamErrorResponse(String error) {
CommonResponse apiResponse = new CommonResponse();
apiResponse.setStatus(RESULT_CODE_PARAM_ERROR);
apiResponse.setMsg(error);
return apiResponse;
}
}

对于前台统一的回复三个参数,状态,状态代码,具体信息------CommonResponse

返回前端的主要是下面这个实体信息

package com.controller.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.io.Serializable;
import java.util.List;

public class CommonResponse implements Serializable {
private static final long serialVersionUID = -2106907432523868421L;

private Integer status;

private String msg;

private Object data;

public Integer getStatus() {
return status;
}

public void setStatus(Integer status) {
this.status = status;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public void setBindingResult(BindingResult... results) {
this.msg = this.getErrors(results);
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = JSONObject.toJSON(data);
}

protected String getErrors(BindingResult[] results) {
StringBuffer str = new StringBuffer();
for (int i = 0; i < results.length; i++) {
BindingResult result = results[i];
if (result.hasErrors()) {
List<FieldError> errors = result.getFieldErrors();
for (int j = 0; j < errors.size(); j++) {
String mm = errors.get(j).getDefaultMessage();
str.append(",").append(mm);
}
}
}
return str.toString().replaceFirst(",", "");
}

}



举报

相关推荐

0 条评论