RESTFul风格举例:实体model为User对象,定义路径为
- GET /users 查询所有
- GET /users/{id} 根据主键查询单个
- POST /users 新增,参数为对象值
- PUT /users/{id} 修改,参数为对象值
- DELETE /users/{id} 删除
响应对象Result.java
package com.ww.common.constant;
import java.io.Serializable;
/**
* 响应对象
*
* @Auther: Ace Lee
* @Date: 2019/3/5 16:35
*/
public class Result<T> implements Serializable {
private boolean success;
private String error;
private T data;
public Result(T data){
this.success=true;
this.data=data;
}
public static Result error(String error){
return new Result<>(WwCommonInfo.FAIL,error,null);
}
public static Result sucess(){
return new Result<>(WwCommonInfo.SUCCESS,"",null);
}
public Result(boolean success,String error,T data){
this.success=success;
this.error=error;
this.data=data;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
父类接口BaseController.java
package com.ww.common.web;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.ww.common.constant.Result;
import com.ww.common.constant.UserInfo;
import com.ww.common.constant.WwCommonInfo;
import com.ww.common.error.ErrorMessage;
import com.ww.common.json.JacksonUtil;
import com.ww.common.util.AESForNodejs;
import com.ww.common.util.BusinessUtils;
import com.ww.common.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
/**
*
* RESTFul服务接口基类
*
* @auther: Ace Lee
* @date: 2019/3/4 16:23
*/
@Api(value = "服务接口API",description = "服务接口API")
@Slf4j
@Data
@CrossOrigin(origins = "*", maxAge = 3600)
public abstract class BaseRestController<T,E> {
protected String ID="WW_XH";//序号
protected String DELETE="WW_SFSC";//是否删除
protected String CREATE_TIME="WW_CJSJ";//创建时间
protected String UPDATE_TIME="WW_XGSJ";//修改时间
protected String CREATE_USER="WW_CJR";//创建人
protected String UPDATE_USER="WW_XGR";//修改人
protected String CREATE_CODE="WW_CJR_BH";//创建人编号
protected String UPDATE_CODE="WW_XGR_BH";//修改人编号
protected String UNIT_CODE="WW_CJDW_BH";//创建单位编号
protected String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Autowired
private BaseRestMapper<T,E> baseRestMapper;
@ApiOperation(value = "查询")
@GetMapping("/{id}")
public Result get(HttpServletRequest request, @PathVariable String id){
Result result;
log.info("主键查询请求参数:{}", id);
UserInfo userInfo = getUser(request);
if (null==userInfo){
return Result.error(ErrorMessage.E_002.getErrDesc());
}
try {
T entity=baseRestMapper.selectByPrimaryKey(id);
Map<String, Object> object = BusinessUtils.object2UpperCase(entity);
log.info("主键查询结果:{}", object);
//查询后做些事
afterGet(id,object,userInfo);
if(null==entity){
result = Result.error(ErrorMessage.E_003.getErrDesc());
}else {
result = new Result<>(object);
}
} catch (Exception e) {
log.error("主键查询异常:{}", Throwables.getStackTraceAsString(e));
result=Result.error(ErrorMessage.E_999.getErrDesc());
}
return result;
}
@ApiOperation(value = "新增")
@PostMapping("")
@Transactional
public Result add(HttpServletRequest request, @RequestBody Map<String, Object> params){
Result result;
int res = 0;
if (null==params || params.isEmpty()){
return Result.error(ErrorMessage.E_001.getErrDesc());
}
log.info("新增请求参数:{}", params);
UserInfo userInfo = getUser(request);
if (null==userInfo){
return Result.error(ErrorMessage.E_002.getErrDesc());
}
try {
//保存前做些事
beforeAdd(params,userInfo);
setCreateParams(params, userInfo, getDATE_TIME_FORMAT());
String json = JacksonUtil.bean2Json(params);
T entity = JacksonUtil.json2Bean(json, new TypeReference<T>() {});
log.info("新增参数:{}", JacksonUtil.bean2Json(entity));
res=baseRestMapper.insertSelective(entity);
//保存后做些事
afterAdd(params,userInfo);
result=new Result<>(params.get(getID()));
} catch (Exception e) {
log.error("新增异常:{}", Throwables.getStackTraceAsString(e));
throw new RuntimeException(ErrorMessage.E_999.getErrDesc());
}
return result;
}
@ApiOperation(value = "修改")
@PutMapping("/{id}")
@Transactional
public Result update(HttpServletRequest request,@PathVariable String id, @RequestBody Map<String,Object> params){
Result result;
int res = 0;
if (null==params || params.isEmpty()){
return Result.error(ErrorMessage.E_001.getErrDesc());
}
log.info("修改请求参数:{},{}", id,params);
UserInfo userInfo = getUser(request);
if (null==userInfo){
return Result.error(ErrorMessage.E_002.getErrDesc());
}
try {
//修改前做些事
beforeUpdate(params,userInfo);
setUpdateParams(params, userInfo, getDATE_TIME_FORMAT());
params.put(getID(),id);
String json = JacksonUtil.bean2Json(params);
T entity = JacksonUtil.json2Bean(json, new TypeReference<T>() {});
log.info("修改参数:{}", JacksonUtil.bean2Json(entity));
res=baseRestMapper.updateByPrimaryKeySelective(entity);
//修改后做些事
afterUpdate(params,userInfo);
result=Result.sucess();
} catch (Exception e) {
log.error("修改异常:{}", Throwables.getStackTraceAsString(e));
throw new RuntimeException(ErrorMessage.E_999.getErrDesc());
}
return result;
}
@ApiOperation(value = "删除")
@DeleteMapping("/{id}")
@Transactional
public Result delete(HttpServletRequest request,@PathVariable String id){
Result result;
int res = 0;
if (StringUtils.isEmpty(id)){
return Result.error(ErrorMessage.E_001.getErrDesc());
}
log.info("删除请求参数:{}", id);
UserInfo userInfo = getUser(request);
if (null==userInfo){
return Result.error(ErrorMessage.E_002.getErrDesc());
}
try {
//删除前做些事
beforeDelete(id,userInfo);
if (isDeleteLogical()){
Map<String,Object> params = Maps.newHashMap();
setUpdateParams(params, userInfo, getDATE_TIME_FORMAT());
params.put(getID(),id);
params.put(getDELETE(),true);//逻辑删除
String json = JacksonUtil.bean2Json(params);
T entity = JacksonUtil.json2Bean(json, new TypeReference<T>() {});
log.info("删除的参数:{}", JacksonUtil.bean2Json(entity));
res=baseRestMapper.updateByPrimaryKeySelective(entity);
}else {
res=baseRestMapper.deleteByPrimaryKey(id);//物理删除
}
//删除后做些事
afterDelete(id,userInfo);
result=Result.sucess();
} catch (Exception e) {
log.error("删除异常:{}", Throwables.getStackTraceAsString(e));
throw new RuntimeException(ErrorMessage.E_999.getErrDesc());
}
return result;
}
/**
* 保存对象前的业务处理
*
* @param: params
* @param: entity
* @param: userInfo
*/
protected void beforeAdd(Map<String, Object> params, UserInfo userInfo){
}
/**
* 修改对象前的业务处理
*
* @param: params
* @param: entity
* @param: userInfo
*/
protected void beforeUpdate(Map<String, Object> params, UserInfo userInfo){
}
/**
* 删除对象前的业务处理
*
* @param: id
*/
protected void beforeDelete(String id, UserInfo userInfo){
}
/**
* 主键查询对象后的业务处理
*
* @param: params
* @param: entity
* @param: userInfo
*/
protected void afterGet(String id, Map<String, Object> entity, UserInfo userInfo){
}
/**
* 保存对象后的业务处理
*
* @param: params
* @param: entity
* @param: userInfo
*/
protected void afterAdd(Map<String, Object> params, UserInfo userInfo){
}
/**
* 修改对象后的业务处理
*
* @param: params
* @param: entity
* @param: userInfo
*/
protected void afterUpdate(Map<String, Object> params, UserInfo userInfo){
}
/**
* 删除对象后的业务处理
*
* @param: id
*/
protected void afterDelete(String id, UserInfo userInfo){
}
/**
* 是否逻辑删除
* 默认为true。
* 如果子类需要物理删除,请重写该方法,返回false
*
* @return true
*/
protected boolean isDeleteLogical(){
return true;
}
/**
* 获取用户信息
*
* @param: request
* @return: userInfo
*/
protected UserInfo getUser(HttpServletRequest request){
UserInfo userInfo = null;
try {
//获取token
String token = request.getHeader(WwCommonInfo.TOKEN_KEY);
log.info("token = {}",token);
//token解密
if (!StringUtils.isEmpty(token)){
String decrypt = AESForNodejs.decrypt(token, WwCommonInfo.TOKEN_PRIVATE_KEY);
log.info("token decrypt = {}",decrypt);
userInfo = JacksonUtil.json2Bean(decrypt, new TypeReference<UserInfo>() {});
}
} catch (Exception e) {
log.info("token异常:{}", Throwables.getStackTraceAsString(e));
}
return userInfo;
}
/**
* 新增设默认值
*
* @param: params userInfo
*/
protected void setCreateParams(Map<String, Object> params, UserInfo userInfo, String dateTimeFormat) {
Object WW_XH = params.get(getID());
if (null==WW_XH){
params.put(getID(), UUID.randomUUID());
}else {
if (WW_XH instanceof String){
String xh = (String) WW_XH;
if (StringUtils.isEmpty(xh)){
params.put(getID(), UUID.randomUUID());
}
}
}
params.put(getUNIT_CODE(), userInfo.getUnitId());
params.put(getCREATE_CODE(), userInfo.getId());
params.put(getCREATE_USER(), userInfo.getRealname());
params.put(getCREATE_TIME(), DateUtils.getCurrentDateTime(dateTimeFormat));
params.put(getUPDATE_CODE(), userInfo.getId());
params.put(getUPDATE_USER(), userInfo.getRealname());
params.put(getUPDATE_TIME(), DateUtils.getCurrentDateTime(dateTimeFormat));
params.put(getDELETE(), false);
}
/**
* 修改设默认值
*
* @param: params userInfo
*/
protected void setUpdateParams(Map<String, Object> params, UserInfo userInfo, String dateTimeFormat) {
params.put(getUPDATE_USER(), userInfo.getRealname());
params.put(getUPDATE_CODE(), userInfo.getId());
params.put(getUPDATE_TIME(), DateUtils.getCurrentDateTime(dateTimeFormat));
}
}