# ne4common-spring-boot-starter **Repository Path**: 72/ne4common-spring-boot-starter ## Basic Information - **Project Name**: ne4common-spring-boot-starter - **Description**: ne公共类封装工具包 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-07-03 - **Last Updated**: 2022-05-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 封装了一些公共代码 ### BaseAction ``` java /** * 获取查询参数 */ protected JSONObject getSrh(){ Enumeration names = request.getParameterNames(); JSONObject srh = new JSONObject(); while (names.hasMoreElements()) { String name = names.nextElement(); if (name.startsWith("srh_")) { String key = name.substring(4); String val = request.getParameter(name); srh.put(key, val); } } return srh; } /** * 获取分页数据 */ public Page getPage() { Page page = new Page(); Integer pageNumber = ChkUtil.getInteger(request.getParameter("pageNumber")); Integer pageSize = ChkUtil.getInteger(request.getParameter("pageSize")); if (pageNumber > 0) { page.setPageNumber(pageNumber); } if (pageSize > 0) { page.setPageSize(pageSize); } return page; } ``` ### BaseService 共分为两部分: - 可供Action直接使用的方法:public 方法 - 为Service类提供便利的方法:protected 方法 **可供Action直接使用的方法** ```java /** * 新增一条数据,生成insert语句时,为null字段不会生成 * * @param model 数据 * @return 返回更新行数 * @see BaseMySQLService#saveTemplateObj(com.tmsps.ne4spring.orm.model.DataModel) */ @Transactional(rollbackFor = Exception.class) public int saveTemplateObj(T model){} /** * 新增一条数据,生成insert语句时,会将数据库字段置为null * 数据库设置了默认值时,不建议使用此方法 * * @param model 数据 * @return 返回更新行数 * @see BaseMySQLService#saveObj(com.tmsps.ne4spring.orm.model.DataModel, boolean) */ @Transactional(rollbackFor = Exception.class) public int save(T model){} /** * 根据id查询一条数据 * 请实现modelHasDelete方法协助完成查询功能 * * @param id 数据主键 * @return 数据 * @see BaseService#modelHasDelete(com.tmsps.ne4spring.orm.model.DataModel) */ public T findOne(String id){} /** * 获取列表分页数据 * 请实现getFindPageParamBean方法协助完成查询功能 * * @param pageNumber 当前页码,从1开始 * @param pageSize 页面容量 * @param srh 查询参数 * @return 结果数据 * @see BaseService#getFindPageParamBean(com.alibaba.fastjson.JSONObject) */ public PageVo findPage(int pageNumber, int pageSize, JSONObject srh) {} /** * 获取列表分页数据 * 请实现getFindPageParamBean方法协助完成查询功能 * * @param page 分页参数 * @param srh 查询参数 * @return 结果数据 * @see BaseService#getFindPageParamBean(com.alibaba.fastjson.JSONObject) */ public PageVo findPage(Page page, JSONObject srh) {} /** * 获取列表数据 * 请实现getFindPageParamBean方法协助完成查询功能 * * @param srh 查询参数 * @return 结果数据 * @see BaseService#getFindPageParamBean(com.alibaba.fastjson.JSONObject) */ public List findList(JSONObject srh) {} /** * 增量更新数据 * * @param model 数据 * @return 结果 */ @Transactional(rollbackFor = Exception.class) public int updateChangeObj(T model){} /** * 删除数据,如果数据不存在会抛出异常,以便自定义返回信息 * 请实现notFoundModelException完成删除功能 * * @param id 数据Id * @return 更新数据的行数 */ @Transactional(rollbackFor = Exception.class) public int delete(String id){} /** * 删除数据 * 请实现change2DeleteStatus完成删除功能 * * @param model 数据实体 * @return 更新数据行数 */ @Transactional(rollbackFor = Exception.class) public int delete(T model){} ``` **为Service类提供便利的方法** ```java /** * 只对子类开放,方便开发 * 提供查询sql,只返回列表中第一个元素 * * @param pb 封装了sql信息的对象 * @return 返回查询结果 */ protected T findOneByParamBean(ParamBean pb) {} /** * 查询并返回列表数据 * * @param pb 封装了sql信息的对象 * @return 返回列表数据 */ protected List findListByParamBean(ParamBean pb) {} /** * 查询分页数据 * * @param page 分页数据 * @param pb sql数据 * @return 分页结果 */ protected PageVo findPageByParamBean(Page page, ParamBean pb) {} /** * 查询分页数据 * * @param pageNumber 当前页码 从1开始 * @param pageSize 页面容量 * @param pb sql数据 * @return 分页结果 */ protected PageVo findPageByParamBean(int pageNumber, int pageSize, ParamBean pb) {} ``` ### 添加了全局Long处理 AppConfig ```java /** * 解决long类型精度丢失问题 * @author jiangtao */ @Configuration public class AppConfig { public static final ObjectMapper JACKSON_MAPPER = new ObjectMapper(); static { SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); simpleModule.addSerializer(Double.class, ToStringSerializer.instance); simpleModule.addSerializer(Double.TYPE, ToStringSerializer.instance); JACKSON_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); JACKSON_MAPPER.registerModule(simpleModule); } @Bean public ObjectMapper getObjectMapper(){ return JACKSON_MAPPER; } } ``` ### 在配置文件中配置errorCode ExceptionCodeConfiguration ```java /** * 读取配置文件中的错误码 * @author jiangtao */ @ConfigurationProperties(prefix = "result") @PropertySource(value = "classpath:config/error-code.properties") @Component public class ExceptionCodeConfiguration { private Map codes = new HashMap<>(); public Map getCodes() { return codes; } public void setCodes(Map codes) { this.codes = codes; } public String getMessage(String code){ return codes.get(code); } } ``` resources/config/error-code.properties ```properties result.codes[N0100]=项目模块错误 result.codes[N0101]=项目信息不存在 result.codes[N0102]=新增项目失败 ``` ### 全局异常定义 #### AppException 需要传入error-code.properties中的错误代码。会自动封装成统一返回格式,返回请求。 ```java /** * 注,该异常不记录是志输出,使用前需自行输出错误日志 * @author jiangtao */ public class AppException extends RuntimeException { /** * 对应错误文件中的code */ protected String code; public AppException(String code) { this.code = code; } public String getAppResponseCode(){ return code; } } ``` ### ServiceException 继承自AppException,在service处理过程中,可以直接抛出异常,提前结束请求。 ```java /** * @author jiangtao */ public class ServiceException extends AppException { public ServiceException(String code) { super(code); } } ``` ### 统一返回码处理 result/**ResponseBean**: 统一返回数据格式 result/**ResponseCodeEnum**:全局的异常状态 只列出了部分: ```java /** * com.nuoyun.pro.model.result * 返回状态码 * 2020/5/26 * 2020 nuoyun All rights reserved. * @author dongxujiao * @version V1.0 */ @SuppressWarnings("unused") public enum ResponseCodeEnum { /** * 一级宏观错误码 * B0001--系统执行出错 */ EX_SYSTEM("B0001", "系统执行出错"), /** * 二级宏观错误码 * B0100--系统执行超时 */ EX_SYSTEM_EXECUTION("B0100", "系统执行超时"), /** * B0101--系统订单处理超时 */ EX_SYSTEM_EXECUTION_ORDER_TIMEOUT("B0101", "系统订单处理超时"); ``` ### 全局异常拦截 GlobalExceptionAdvice ```java /** * 全局异常处理 */ @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseBean handleException(HttpServletRequest req, Exception e) { String requestUrl = req.getRequestURI(); String method = req.getMethod(); log.info("请求地址:{} {}", method, requestUrl); log.error("全局捕获异常", e); return new ResponseBean(ResponseCodeEnum.EX_SYSTEM); } /** * 处理自定义异常 * @param e 自定义异常 * @return 自定义返回类型 */ @ExceptionHandler(AppException.class) @ResponseBody public ResponseBean handleAppException(AppException e){ String appResponseCode = e.getAppResponseCode(); return new ResponseBean(appResponseCode, codeConfiguration.getMessage(appResponseCode)); } /** * beanValidation 校验异常处理 * @param req request * @param e 具体的错误 */ @ExceptionHandler({BindException.class}) @ResponseBody public ResponseBean handleBeanValidation(HttpServletRequest req, BindException e) { String requestUrl = req.getRequestURI(); String method = req.getMethod(); List errors = e.getBindingResult().getAllErrors(); String message = this.formatAllErrorMessages(errors); log.info("请求地址:{} {}", method, requestUrl); log.info("参数验证不通过:{}", e.getMessage()); return new ResponseBean(ResponseCodeEnum.EX_USER_REG_PARAMS.getCode(), message); } ```