这篇文章主要讲解了“SpringBoot怎么根据目录路径生成接口的url路径”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot怎么根据目录路径生成接口的url路径”吧!
首先我们新建一个AutoPrefixUrlMapping类,继承自RequestMappingHandlerMapping,用以获取新的url
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(".","/");
}
}
api-package = com.lyn.miniprogram.api
用以声明url的根目录
然后我们创建一个AutoPrefixConfiguration类,用以将AutoPrefixUrlMapping加入Springboot的容器中
@Component
public class AutoPrefixConfiguration implements WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new AutoPrefixUrlMapping();
}
}
测试接口如下:
url会自动带上 /v1的前缀,测试通过!当然,如果目录层级更复杂,通过上述代码也是可以实现的。
springboot正常启动项目,访问接口均正常,新增一接口请求界面路径,访问该接口报错404
idea springboot
http://localhost:8080/cuer/apSw?ad=2893e6fce42&_=161607509 404
百度说是接口所在包放置位置不对,导致接口没被扫描到,但是我的情况是系统原本存在的接口都可以访问到,并且新接口所在位置与旧接口所在位置一致。且查看新接口包与 spring boot启动类的位置符合可被扫描到情况,故排除新接口包放置位置不对的情况
查看后端接口代码写法没错
查看调用后端接口传参是否错误(接口有参数,直接不传参http://localhost:8080/cuer/apSw,打断点 访问接口,可以进入到接口,说明接口没错)断点往下打,发现是return 页面报404 ,比对后发现,页面路径对应根本没页面,修改页面路径重新访问,成功。
@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”;
}
}
}
感谢各位的阅读,以上就是“SpringBoot怎么根据目录路径生成接口的url路径”的内容了,经过本文的学习后,相信大家对SpringBoot怎么根据目录路径生成接口的url路径这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。