映射Servlet到URL模式为/时,资源文件加载失败。

4
我使用NetBeans和Tomcat 7.0.4.2,并想将我的项目的URL地址从localhost:8080/Servlet更改为localhost:8080/。在web.xml中,我将servlet URL地址从<url-pattern>/Servlet</url-pattern>更改为<url-pattern>/</url-pattern>
问题是我现在无法加载资源文件,并在浏览器控制台日志中收到错误信息:
  Failed to load resource: the server responded with a status of 404 (Not Found) (11:45:14:149 | error, network)
  at src/main/webapp/scripts/aui-min_2.0.0.js

资源文件路径为 src/main/webapp/scripts,在JSP文件中使用此路径。
<script type="text/javascript" src="scripts/aui-min_2.0.0.js"></script>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>socialgraphui.Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

src 目录在部署中不存在。任何依赖于它存在的代码都是错误的。 - user207421
相关链接:https://dev59.com/n2855IYBdhLWcg3wy3oc - BalusC
1个回答

1

默认servlet使用的url模式是/,可以加载未被其他servlet映射的静态资源。当你切换到这个模式时,它停止工作了。因此,你应该保留一个servlet映射。

<servlet-mapping>
    <servlet-name>Servlet</servlet-name>
    <url-pattern>/Servlet</url-pattern>
</servlet-mapping>

如果您想从索引页面开始,请使用列在<welcome-file-list>配置中的index.jsp。索引页面可以使用重定向到Servlet。
response.sendRedirect(request.getContextPath() +"/Servlet");

使用Servlet上下文路径来加载静态资源,如下所示:
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/aui-min_2.0.0.js"></script>

谢谢您的回复,Roman。但是在那之后,Tomcat会一直循环部署我的项目,无法停止。 - Matt
好的,请重新部署它。 - Roman C
谢谢Roman,但是还是不起作用。这是我的新web.xml http://pastebin.com/ZZjQ0EgE 现在我可以在localhost:8080/地址上加载我的源代码,但是使用这个解决方案,我无法将变量从Servlet传递到index.jsp文件。在Servlet类中,我尝试将request.getRequestDispatcher("index.jsp").forward(request, response);替换为processRequest方法中的response.sendRedirect("/Servlet");,但仍然无法传递变量。 - Matt
index.jsp 应该只有代码 <%response.sendRedirect("/Servlet");%>。但是你可以转发到另一个页面,以避免无限循环。 - Roman C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接