在/的URL模式上映射Servlet时无法加载资源文件



我使用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>

默认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>

最新更新