您好!欢迎来到爱源码

爱源码

热门搜索: 抖音快手短视频下载   

Springboot代码生成器V2.21版本升级——更新相关依赖版本,添加全局响应解决方案,使用注释控制登录和日志记录等。 <网站源码>

  • 时间:2022-07-06 02:42 编辑: 来源: 阅读:311
  • 扫一扫,手机访问
摘要:Springboot代码生成器V2.21版本升级——更新相关依赖版本,添加全局响应解决方案,使用注释控制登录和日志记录等。 <网站源码>
前言生成器下载地址:http://www.zrxlh.top:8088/coreCode/.源地址:https://gitee.com/zrxjava/codeMan由于工作生活的影响,半年多没有升级博客,代码生成器也没有继续维护。后来朋友给我发私信催我升级。并提出相关优化建议。今天,我终于按照朋友们的建议,着手改进代码生成器。以后我会努力保持健康的升级速度。希望能对大家有所帮助!之前全局跨域配置,每个控制器都会加@CrossOrigin,现在采用整体跨域配置。前者可以灵活控制,后者更简单直接。而跨域一般是为了前后站的方便,所以采用了后者。因为正规环境下的前后台一般会使用nginx作为统一的转发解决方案,跨域的接口会写成本域的接口,然后这些接口会被转发到真实的请求地址,所以不存在跨域的问题。 有一点需要注意(与跨域无关),现在新版goole浏览器加强了安全监控,主要是防止注入攻击。如果发现访问应用程序的地址与应用程序的父地址不同,登录时将无法设置cookies。如果使用session来控制客户的登录,就会出现无法获得session的问题。因为不能设置cookies,所以不会有seesionId,导致登录无效。 也有相应的解决方法:1。打开Chrome设置,禁用Chrome://flags/# same-site-by-default-cookies,然后重启浏览器;2.用token代替cokkie进行验证,也就是我们常用redis保存token进行验证。 跨域配置的代码如下:/* * *跨域配置* * @ author zrx */@ configuration public class CORS config { @ bean public filterration bean < CORS filter & gt;CORS filter(){ urlbasedcorconfigurationsource source = new urlbasedcorconfigurationsource();CORS configuration config = new CORS configuration();config . setallowcredentials(true);config . addallowedorigin(" * ");config . addallowedheader(" token ");config . addallowedheader(" Content-Type ");config . addallowedmethod(" GET ");config . addallowedmethod(" POST ");config . addallowedmethod(" PUT ");config . addallowedmethod(" DELETE ");config . addallowedmethod(" OPTIONS ");config . set maxage(1000 l * 60 * 60);source . registercorsconfiguration("/* * ",config);FilterRegistrationBean & ltCorsFilter & gtbean = new FilterRegistrationBean & lt;& gt(new CORS filter(source));//过滤之前,会在blocker之前执行,所以不会受到blocker bean.setOrder(0)的影响;回豆;}}}添加注释以控制登录和记录。在实际的项目开发中,一个项目的后端往往会有很多API。有些API需要登录认证,而有些则不需要。为了灵活控制,用注释来控制这个。原理很简单。获取拦截器中请求方法的评论信息,登录验证评论是否存在,如果不存在则直接放过。相关代码如下:/* * *此注释用于REST API *如果某个API需要客户端登录,添加此注释* * @ author zrx */@ retention(retention policy . runtime)@ target(element type . method)@ documented public @ interface log in required { } @ Override public void Add interceptors(interceptor registry){ registry . addinterceptor(new handler interceptor(){ @ Override public boolean pre handle(http servlet request请求,HttpServletResponse,对象处理程序)抛出异常log in required log in required = handler method . getmethod annotation(log in required . class);if (null == loginRequired) {返回true}//预请求if (requestmethod.options.name()。equals(request . get method()){ return true;} http session session = request . getsession();User User =(User)session . get attribute(" User ");if(user = = null){ response . set header(" Access-Control-Allow-Origin ",request . get header(" Origin "));response . set header(" Access-Control-Allow-Methods "," * ");response . set header(" Access-Control-Max-Age "," 3600 ");response . set header(" Access-Control-Allow-Credentials "," true ");response . set content type(" application/JSON;charset = utf-8 ");response . setcharacterencoding(" utf-8 ");PrintWriter pw = response . getwriter();pw . write(" { \ " code \ ":"+http servlet response . sc _ unauthorized+",\" status \ ":\" no \ ",\" msg \ ":\ "无授权访问,请登录\ " } ";pw . flush();pw . close();返回false} }返回true} }).addPathPatterns("/** ")。exclude pathmates("/log in "、"/register "、"/login/doLogin "、"/user/register "、"/mystatic/** "、"/druid/** "、"/swagger-resources/** "、"/v2/** "、"/swagger-ui . html/* * ");}使用方法也极其简单,直接将此注释添加到控制器的方法中即可,例如:/* * * query * * @ return */@ API operation(value = " query ")//添加此注释表示需要登录才能调用此方法,然后才能调用@ log in required @ post mapping(value = "/select ")public list < testtable entity & gt;select(@ request body testtable entity entity){ return service . select(entity);}日志注释与登录注释相同。添加日志注释可以实现方法级日志记录。使用方法同上,代码如下:/* * *要记录日志的注释*在需要记录日志的控制器上添加此注释。可以记录日志* * @ author zrx */@ target(element type . method)@ retention(retention policy . runtime)public @ interface记录日志{ string value()default " ";}@Aspect@Componentpublic类logopaspect { private static final Logger Logger = Logger factory . get Logger(logopaspect . class);@ Around(" @ annotation(boot demo . core . annotation . record log)")公共对象进程(ProceedingJoinPoint pjp)抛出Throwable { Class & lt?& gtcurrentClass = pjp.getTarget()。getClass();method signature signature =(method signature)(pjp . get signature());string class name = current class . get simplename();string method name = current class . get method(signature . getname()、signature.getParameterTypes())。getName();Logger.info("=======开始执行:"+class name+"—"+method name+" = = = = = ");object obj = pjp . proceed();Logger.info("======= = = = =执行结束:"+class name+"——"+method name+" = = = = ");返回obj}}}在统一解决响应之前,代码生成器的响应已经被一层一层的抽取出来,返回的信息已经封装在对象中,但是还没有完全解耦。现在,这一对策已被进一步压缩到全球范围。只要控制器需要写业务代码,就不需要去找新的responder对象,进一步降低了耦合度。对于程序异常,它只需要抛出相应的异常。统一的解决方案类会封装异常信息提醒前端客户,代码如下:@ SLF4J @控制器建议@响应体公共类Allexception Handler实现响应体建议{@ Override公共布尔支持(Metho dParameter returnType,Class clazz){ return null = = returnType . getmethodannotation(no pack . Class);}/* * *返回前包装响应内容*/@ override public object beforebodywrite(对象体,方法参数返回类型,MediaType selectedContentType,Class selectedConverterType,ServerHttpRequest,server httpresponse response){ if(media type。APPLICATION _ JSON . equals(selected content type)| | media type。APPLICATION _ JSON _ utf8 . equals(selectedContentType)){ Method Method =(Method)returntype . get executable();if(response entity . class . equals(method . get returntype()){ return body;} if(null = = body){ return response result . success();} if(body instance of response result){ return body;} return responser result . success(body);}返回正文;} .../* * *普通业务异常* * @ paramex * @ return */@ exception handler(business exception . class)public response result business exception handler(http servlet response response,business exception ex){ log . error(ex . getmessage(),ex);response . set status(response status。BUSINESS _ exception . hcode);return response result . failed(ex . get code()、ex . getmessage());}/* * *其他错误* * @ paramex * @ return */@ Exception handler({ Exception . class })public response result Exception(http servlet response响应,Exception ex){ log . error(response status。OTHER_EXCEPTION.valueLog,ex);response . set status(response status。OTHER _ exception . hcode);返回response result . failed(response status。OTHER_EXCEPTION.bCode,ResponseStatus。OTHER _ exception . value zh);}}/* * *请求响应正文* * @ author zrx */@ Data @ Builder @ AllArgsConstructor @ NoArgsConstructorpublic类ResponseResult实现Serializable { private static final long serial version uid = 6041766238120354185 l;私有int代码;私有字符串状态;私有字符串msg私有对象数据;公共静态response result success(){ return success(null);}公共静态ResponseResult成功(对象数据){ return ResponseResult.builder()。状态(响应状态。SUCCESS.valueEn)。msg(ResponseStatus。SUCCESS.valueZh)。代码(ResponseStatus。SUCCESS.bCode)。数据(数据)。build();}公共静态响应结果failed(){ return failed(" failed ");}公共静态ResponseResult失败(String msg) { return失败(ResponseStatus。FAILED.bCode,msg);} public static ResponseResult失败(int code,String msg){ return response result . builder()。状态(响应状态。FAILED.valueEn)。味精(味精)。代码(code)。build();}}/* * *此注释用于REST API * *如果一个API的返回不需要ResponseWrapper进行包装,添加此注释* * @ author zrx */@ retention(retention policy . runtime)@ target(element type . method)@ documented public @ interface pack { }代码如上所示,通过在ResponseBodyAdvice接口中实现beforeBodyWrite方法,可以对返回的内容进行打包。spring始终贯穿着aop的核心思想。 如果不想包装响应内容,可以在控制器的方法中添加NoPack注释来实现。原理与上面提到的登录注释相同:实现ResponseBodyAdvice的supports方法。如果没有NoPack注释,则包装响应内容。spring已经帮我们实现了整体功能,我们只需要重写方法加入相关业务就可以了。 swagger优化的swagger官方风格很丑,所以增加了新的swagger风格依赖。样式如下:swagger依赖关系如下: 生成的代码显示了v2.21版本的代码显示了结论。这次升级的细节到这里就结束了,其中响应的统一解决方案相当有意义。感谢大家的宝贵意见,工作忙,生活琐事多,升级可能不会太及时。请原谅我。下次见!下载地址:http://www.zrxlh.top:8088/coreCode/.源地址:https://gitee.com/zrxjava/codeMan


  • 全部评论(0)
资讯详情页最新发布上方横幅
最新发布的资讯信息
【域名/主机/服务器|】qq邮箱提醒在哪里打开(2024-06-04 18:58)
【技术支持|常见问题】1556原创ng8文章搜索页面不齐(2024-05-01 14:43)
【技术支持|常见问题】1502企业站群-多域名跳转-多模板切换(2024-04-09 12:19)
【技术支持|常见问题】1126完美滑屏版视频只能显示10个(2024-03-29 13:37)
【技术支持|常见问题】响应式自适应代码(2024-03-24 14:23)
【技术支持|常见问题】1126完美滑屏版百度未授权使用地图api怎么办(2024-03-15 07:21)
【技术支持|常见问题】如何集成阿里通信短信接口(2024-02-19 21:48)
【技术支持|常见问题】算命网微信支付宝产品名称年份在哪修改?风水姻缘合婚配对_公司起名占卜八字算命算财运查吉凶源码(2024-01-07 12:27)
【域名/主机/服务器|】帝国CMS安装(2023-08-20 11:31)
【技术支持|常见问题】通过HTTPs测试Mozilla DNS {免费源码}(2022-11-04 10:37)

联系我们
Q Q:375457086
Q Q:526665408
电话:0755-84666665
微信:15999668636
联系客服
企业客服1 企业客服2 联系客服
86-755-84666665
手机版
手机版
扫一扫进手机版
返回顶部