SpringBoot访问不到webapp下的内容

springboot 在idea多模块下 子模块的web项目用内置tomcat启动访问jsp报404
问题描述:最近公司换spring boot 做微服务开发。多个微服务按模块导入导入到idea。之前是单独的项目导入。能正常启动和正常访问。换到idea的项目–模块结构之后。发现用内置tomcat启动web项目无法访问到jsp页面了。(ps:打成war包到外面tomcat启动是没有问题。只是不服,发现这个奇葩的问题没找到原因心中不爽。)

问题分析:无法访问jsp,很自然想到:一是路径有没有映射对?二是文件不存在。检查一遍之后发现映射没有问题,文件也存在。这就比较奇葩了。唯有看一下springboot在启动的时候如何定义web root的路径。跟一下springboot的tomcat启动包的源码:

/**

  • Returns the absolute document root when it points to a valid directory, logging a
  • warning and returning {@code null} otherwise.
  • @return the valid document root
    */
    protected final File getValidDocumentRoot() {
    File file = getDocumentRoot();
    // If document root not explicitly set see if we are running from a war archive
    file = file != null ? file : getWarFileDocumentRoot();
    // If not a war archive maybe it is an exploded war
    file = file != null ? file : getExplodedWarFileDocumentRoot();
    // Or maybe there is a document root in a well-known location
    file = file != null ? file : getCommonDocumentRoot();
    if (file == null && this.logger.isDebugEnabled()) {
    this.logger
    .debug(“None of the document roots " + Arrays.asList(COMMON_DOC_ROOTS)
    + " point to a directory and will be ignored.”);
    }
    else if (this.logger.isDebugEnabled()) {
    this.logger.debug("Document root: " + file);
    }
    return file;
    }
    发现有三种取路径方式。war包 getWarFileDocumentRoot,导出包 getExplodedWarFileDocumentRoot,和文档 getCommonDocumentRoot。内置tomcat启动应该属于第三种。跟进去第三种发现:

private static final String[] COMMON_DOC_ROOTS = { “src/main/webapp”, “public”,
“static” };
private File getCommonDocumentRoot() {
for (String commonDocRoot : COMMON_DOC_ROOTS) {
File root = new File(commonDocRoot);
if (root != null && root.exists() && root.isDirectory()) {
return root.getAbsoluteFile();
}
}
return null;
}
写死从上面配置的3个目录去取doc路径。

看到这里问题就明了。关键是

File root = new File(commonDocRoot);
if (root != null && root.exists() && root.isDirectory()) {
return root.getAbsoluteFile();
}
File root = new File(“src/main/webapp”) 的是 这个相对路径的前缀是取哪里的。

百度得知 取的是

System.getProperty(“user.dir”)
相当于 File root = new File(System.getProperty(“user.dir”)+“src/main/webapp”);

然后 debug 打印一下 System.getProperty(“user.dir”) 发现 是定位到了 项目那层 而不是模块那层

解决方法:既然发现了问题,解决就简单。这里采用的是直接在启动项里面增加配置参数,将"user.dir" 定位到模块里面。

在这里插入图片描述

问题解决。

最后:因为对tomcat的启动顺序不了解。跟这个过程的时候走了不少弯路。采用了最笨的方法,在后面层层倒推一直找到上面设置doc路径的方法。如果熟悉原理,直接从开始就定位到那个方法就很快能解决了。所以记录下来。避免自己或有遇到同样问题的人少走弯路。

附另一种解决办法:直接用下面的插件启动也可以在这里插入图片描述
原帖地址:https://blog.csdn.net/qq_34657993/article/details/79070084

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值