//基础Controller
package com.mydao.tourist.base.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mydao.tourist.base.constant.HttpStatus;
import com.mydao.tourist.base.baseVo.PageVo;
import com.mydao.tourist.base.exception.FileServerException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 基础Controller
* @author wzq
*/
public class BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);
private static final String TOKEN_NON_EXISTENT = "Missing cookie 'token'";
/** 设置成功响应 */
protected ResponseEntity<Object> success(Object data) {
return responseEntity(HttpStatus.OK,data,HttpStatus.OK.msg());
}
protected ResponseEntity<Object> success(String msg) {
return responseEntity(HttpStatus.OK,null,msg);
}
protected ResponseEntity<Object> success() {
return responseEntity(HttpStatus.OK,null,HttpStatus.OK.msg());
}
protected ResponseEntity<Object> success(Object data,String msg) {
return responseEntity(HttpStatus.OK,data,msg);
}
/** 设置失败响应 */
protected ResponseEntity<Object> error(Object data) {
return responseEntity(HttpStatus.BAD_REQUEST,data,HttpStatus.BAD_REQUEST.msg());
}
protected ResponseEntity<Object> error(String msg) {
return responseEntity(HttpStatus.BAD_REQUEST,null,msg);
}
protected ResponseEntity<Object> error(HttpStatus code ){
return responseEntity(code,null,code.msg());
}
protected ResponseEntity<Object> error() {
return responseEntity(HttpStatus.BAD_REQUEST,null,HttpStatus.BAD_REQUEST.msg());
}
protected ResponseEntity<Object> error(Object data,String msg) {
return responseEntity(HttpStatus.BAD_REQUEST,data,msg);
}
/** 设置响应代码 */
protected ResponseEntity<Object> responseEntity(HttpStatus code, Object data, String msg) {
Map<String,Object> map = Maps.newHashMap();
if (data != null) {
if (data instanceof Page) {
Page<?> page = (Page<?>) data;
PageVo pageVo = new PageVo();
//当前页
pageVo.setCurrentPage(page.getCurrent());
//每页显示数据条数
pageVo.setPageSize(page.getSize());
//总页数
pageVo.setTotalPages(page.getPages());
//总条数
pageVo.setTotalRecord(page.getTotal());
map.put("data", page.getRecords());
map.put("pageVo", pageVo);
} else if (data instanceof List<?>) {
map.put("data", data);
} else {
map.put("data", data);
}
}
map.put("code", code.value());
map.put("msg", msg);
map.put("timestamp", System.currentTimeMillis());
return ResponseEntity.ok()
// .header("Access-Control-Allow-Origin","*")
.contentType(MediaType.APPLICATION_JSON)
.body(map);
}
/** 异常处理 */
@ExceptionHandler(Exception.class)
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
throws Exception {
Map<String,Object> map = Maps.newHashMap();
int status = 0;
// 方法级别shiro权限校验失败时异常信息处理
if(ex instanceof FileServerException) {
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
String message = StringUtils.isEmpty(ex.getMessage()) ? ex.getCause().getMessage() : ex.getMessage();
map.put("msg",message);
map.put("code", HttpStatus.NSOP_UPLOAD_FAIL.value());
} else if(ex instanceof MethodArgumentNotValidException){
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
map.put("code", HttpStatus.VALIDATED_FAIL.value());
MethodArgumentNotValidException mane = (MethodArgumentNotValidException)ex;
BindingResult bindingResult = mane.getBindingResult();
List<String> errorMessage = Lists.newArrayList();
List<FieldError> fes = bindingResult.getFieldErrors();
for (FieldError fe : fes) {
errorMessage.add(fe.getDefaultMessage());
}
map.put("msg", Joiner.on(",").join(errorMessage));
} else if(ex instanceof ServletRequestBindingException) {
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
if(StringUtils.contains(ex.getMessage(),TOKEN_NON_EXISTENT)) {
status = HttpStatus.UNAUTHORIZED.value();
map.put("code", HttpStatus.UNAUTHORIZED.value());
String message = StringUtils.isEmpty(ex.getMessage()) ? ex.getCause().getMessage() : ex.getMessage();
map.put("msg",message);
}
}
else if(ex instanceof RuntimeException) {
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
String message = StringUtils.isEmpty(ex.getMessage()) ? ex.getCause().getMessage() : ex.getMessage();
map.put("msg",message);
}
if(status == 0) {
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
map.put("msg", HttpStatus.INTERNAL_SERVER_ERROR.msg());
}
ex.printStackTrace();
LOGGER.error(ex.getMessage(),ex);
response.setContentType("application/json;charset=UTF-8");
// response.setHeader("Access-Control-Allow-Origin","*");
response.setStatus(status);
map.put("timestamp", System.currentTimeMillis());
response.getOutputStream().write(new ObjectMapper().writeValueAsString(map).getBytes());
}
}
BaseResult
package com.mydao.tourist.base;
import com.mydao.tourist.base.constant.HttpStatus;
import lombok.Builder;
import java.io.Serializable;
/**
* @author wzq
* todo 统一使用该返回对象
* @date 2023-7-17 11:12:15
*/
@Builder
public class BaseResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private String msg;
private Long timestamp;
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static <T> BaseResult<T> success(T data) {
return BaseResult.<T>builder().data(data).msg(HttpStatus.OK.msg())
.timestamp(System.currentTimeMillis())
.code(HttpStatus.OK.value()).build();
}
public static <T> BaseResult<T> success(String msg) {
return BaseResult.<T>builder().msg(msg)
.timestamp(System.currentTimeMillis())
.code(HttpStatus.OK.value()).build();
}
public static <T> BaseResult<T> success(T data, String msg) {
return BaseResult.<T>builder().msg(msg)
.data(data)
.timestamp(System.currentTimeMillis())
.code(HttpStatus.OK.value()).build();
}
public static <T> BaseResult<T> error(T data) {
return BaseResult.<T>builder().data(data).msg(HttpStatus.BAD_REQUEST.msg())
.timestamp(System.currentTimeMillis())
.code(HttpStatus.BAD_REQUEST.value()).build();
}
public static <T> BaseResult<T> error(String msg) {
return BaseResult.<T>builder().msg(msg)
.timestamp(System.currentTimeMillis())
.code(HttpStatus.BAD_REQUEST.value()).build();
}
public static <T> BaseResult<T> error(T data, String msg) {
return BaseResult.<T>builder().msg(msg)
.data(data)
.timestamp(System.currentTimeMillis())
.code(HttpStatus.BAD_REQUEST.value()).build();
}
}
示例:
controller:
package com.mydao.tourist.guide.controller;
import com.alibaba.fastjson.JSON;
import com.mydao.tourist.base.BaseResult;
import com.mydao.tourist.guide.service.TouristPoiMonitorService;
import com.mydao.tourist.guide.vo.req.TouristPoiMonitorReqVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Author wzq
* @Version 1.0
* @Description //TODO TODO 示例
* @Date 2023/7/4
**/
@RestController
@RequestMapping("/testController")
@Api(value = "/testController", tags = "示例管理", produces = MediaType.ALL_VALUE)
public class TestController{
private static final Logger log = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testService ;
@PostMapping("/saveOrUpdate")
@ApiOperation(value = "保存或编辑", notes = "保存或编辑", httpMethod = "POST")
public BaseResult<Boolean> thisSaveOrUpdate(@RequestBody TouristPoiMonitorReqVo touristPoiCameraReqVo) {
try {
log.debug("开始请求【示例管理】 保存接口:touristPoiCameraReqVo,入参为{}", JSON.toJSONString(touristPoiCameraReqVo));
return testService .thisSaveOrUpdate(touristPoiCameraReqVo);
} catch (Exception e) {
log.error("请求【示例管理】的保存或编辑,保存异常 {}", e);
return BaseResult.error("保存失败!");
}
}
/**
* 列表查询
*/
@PostMapping(value = "/list")
@ApiOperation(value = "列表查询", notes = "列表查询", httpMethod = "POST")
public BaseResult<List<TouristPoiMonitorReqVo>> thisList(TouristPoiMonitorReqVo touristPoiCameraReqVo) {
try {
log.debug("开始请求【POI跟摄像头绑定表管理】列表查询 :touristPoiAreaRelationReqVo,入参为{}", JSON.toJSONString(touristPoiCameraReqVo));
return BaseResult.success(touristPoiCameraService.thisList(touristPoiCameraReqVo));
} catch (Exception e) {
log.error("请求【POI跟摄像头绑定表管理】列表查询 异常 {}", e);
return BaseResult.error("删除失败!");
}
}
}
//service
package com.mydao.tourist.guide.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mydao.tourist.base.BaseResult;
import com.mydao.tourist.base.baseVo.PageReqVo;
import com.mydao.tourist.guide.domain.TouristPoi;
import com.mydao.tourist.guide.domain.TouristPoiMonitor;
import com.mydao.tourist.guide.vo.req.TouristPoiMonitorReqVo;
import com.mydao.tourist.guide.vo.resp.TouristVehicleMonitoringRespVo;
import java.util.List;
/**
* @Author wzq
* @Version 1.0
* @Description //TODO 示例服务类
* Test为实体
* @Date 2023/7/12
**/
public interface TestService extends IService<Test> {
}
//ServiceImpl
package com.mydao.tourist.guide.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author wzq
* @Version 1.0
* @Description //TODO
* @Date 2023/7/12
**/
@Slf4j
@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, Test> implements TestService {
}
//mapper
package com.mydao.tourist.guide.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mydao.tourist.guide.domain.TouristAreaAppPoi;
import org.apache.ibatis.annotations.Mapper;
/**
* @Author wzq
* @Version 1.0
* @Description //TODO
* @Date 2023/1/18
**/
@Mapper
public interface TestMapper extends BaseMapper<Test> {
}
模板示例:
package com.mydao.tourist..controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mydao.common.base.baseVo.BaseResult;
import com.mydao.common.base.baseVo.PageReqVo;
import com.mydao.common.base.controller.BaseController;
import com.mydao.tourist..service.InfoService;
import com.mydao.tourist..vo.req.InfoReqVo;
import com.mydao.tourist..vo.resp.InfoRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Author wzq
* @Version 1.0
* @Description //TODO 信息管理
* @Date 2022/12/1
**/
@RestController
@RequestMapping("/Info")
@Api(value = "/Info", tags= "信息管理", produces = MediaType.ALL_VALUE)
public class InfoController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(InfoController.class);
@Autowired
private InfoService InfoService;
/**
* 分页
*/
@PostMapping(value = "/page")
@ApiOperation(value = "分页数据查询", notes = "分页数据查询")
public BaseResult<IPage<InfoRespVo>> Page(@RequestBody PageReqVo<InfoReqVo> reqVo) {
return InfoService.thisPage(reqVo);
}
/**
* 列表
*/
@PostMapping(value = "/list")
@ApiOperation(value = "列表数据查询", notes = "列表数据查询")
public BaseResult<List<InfoRespVo>> List(@RequestBody InfoReqVo reqVo) {
return InfoService.thisList(reqVo);
}
/**
* 详情
*/
@GetMapping(value = "/find")
@ApiOperation(value = "根据id查询数据", notes = "根据id查询数据")
public BaseResult<Object> find(@RequestParam("id") Long id) {
return InfoService.thisById(id);
}
/**
* 保存或更新
*/
@PostMapping(value = "/saveOrUpdate")
@ApiOperation(value = "更新或新增数据", notes = "更新或新增数据")
public BaseResult<Object> saveOrUpdate(@RequestBody InfoReqVo reqVo) {
return InfoService.thisSaveOrUpdate(reqVo);
}
/**
* 删除
*/
@GetMapping(value = "/delete")
@ApiOperation(value = "根据id删除数据", notes = "根据id删除数据")
public BaseResult<Object> delete(@RequestParam("id") Long id) {
return InfoService.thisDelete(id);
}
}