SpringBoot如何根据目录路径生成接口的url路径
这篇文章主要介绍了SpringBoot如何根据目录路径生成接口的url路径,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
目录
根据目录路径生成接口的url路径
配置文件application.proprties如下
springboot接口请求界面路径返404
接口没被扫描到
配置或代码写法问题
最后
根据目录路径生成接口的url路径
首先我们新建一个AutoPrefixUrlMapping类,继承自RequestMappingHandlerMapping,用以获取新的url
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping { // 从配置文件中读取根目录 @Value ( "${api-package}" ) private String apiPackagePath; @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo mappingInfo = super .getMappingForMethod(method, handlerType); if (mappingInfo != null ){ String prefix = this .getPrefix(handlerType); RequestMappingInfo newMappingInfo = RequestMappingInfo.paths(prefix).build().combine(mappingInfo); return newMappingInfo; } return mappingInfo; } // 获取前缀 private String getPrefix(Class<?> handlerType){ String packageName = handlerType.getPackage().getName(); String newPath = packageName.replaceAll( this .apiPackagePath, "" ); return newPath.replace( "." , "/" ); } } |
配置文件application.proprties如下
1 | api- package = com.lyn.miniprogram.api |
用以声明url的根目录
然后我们创建一个AutoPrefixConfiguration类,用以将AutoPrefixUrlMapping加入Springboot的容器中
1 2 3 4 5 6 7 | @Component public class AutoPrefixConfiguration implements WebMvcRegistrations { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new AutoPrefixUrlMapping(); } } |
测试接口如下:
url会自动带上 /v1的前缀,测试通过!当然,如果目录层级更复杂,通过上述代码也是可以实现的。
springboot接口请求界面路径返404
springboot正常启动项目,访问接口均正常,新增一接口请求界面路径,访问该接口报错404
idea springboot
http://localhost:8080/cuer/apSw?ad=2893e6fce42&_=161607509 404
接口没被扫描到
百度说是接口所在包放置位置不对,导致接口没被扫描到,但是我的情况是系统原本存在的接口都可以访问到,并且新接口所在位置与旧接口所在位置一致。且查看新接口包与 spring boot启动类的位置符合可被扫描到情况,故排除新接口包放置位置不对的情况
配置或代码写法问题
查看后端接口代码写法没错
查看调用后端接口传参是否错误(接口有参数,直接不传参http://localhost:8080/cuer/apSw,打断点 访问接口,可以进入到接口,说明接口没错)断点往下打,发现是return 页面报404 ,比对后发现,页面路径对应根本没页面,修改页面路径重新访问,成功。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | @Slf4j @Controller @RequestMapping (value = { "/customer" }) @AllArgsConstructor public class CerCustomerController { private final PsionsUtil pnsUtil; private final ICCredService crdService; private final ICrEvalService ervice; /** * 跳转到列表界面 * * @return */ @GetMapping ( "/index" ) public String customerCredIndex() { return "/business/customer/index" ; } /** * 跳转到查看界面 * * @return */ @GetMapping ( "/apeShw" ) public String apseShw(String ad, Model model) { model.addAttribute(“apId”, aId); if (“CD”.equals(perUtil.getreTpe())) { return “/bess/cuer/evfo”; } else { CeerVo ceo = creice.gtCByAlyId(ad); model.addAttribute(“cd”, cVo); return “/busis/cr/co”; } } } |
最后
找了挺久,有点坑哦,前端调用写错字母,就乌龙了
以上为个人经验,希望能给大家一个参考
原文链接:https://jiandansuifeng.blog.csdn.net/article/details/104496404