【问题标题】:can't apply external CSS in Struts2无法在 Struts2 中应用外部 CSS
【发布时间】:2026-01-08 09:45:01
【问题描述】:

我有一个带有 struts2 框架的 Java Web 应用程序。在我的index.jsp 文件中,我链接了 CSS 文件,但它没有显示在我的页面中,Error 404: not found 显示在Firebug 中。我在没有 Struts 的情况下测试了一个应用程序,一切都很好。但是当我添加 struts2 库和配置 struts.xmlweb.xml 文件时,CSS 不显示:( 这是我的 index.jsp:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="styles/main.css" rel="stylesheet" type="text/css"/>
</head>

当然,我在href中添加&lt;%@ taglib prefix="s" uri="/struts-tags" %&gt;并尝试&lt;s:url&gt;,但没有看到任何效果。 这是 web.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>

    <web-app 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"
             version="3.0">
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>

        <display-name>HotelSystem</display-name>
            <welcome-file-list>
                <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>

        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>

这是我的 struts.xml 的一部分:

<package name="default" namespace="/" extends="struts-default">
        <action name="index.jsp" class="Actions.Test">
            <result name="success">/index.jsp</result>
        </action>
    </package>

注意:Action.Test 是一个测试操作,总是返回 SUCCESS。

【问题讨论】:

  • 永远不要写我真的需要尽快解决这个问题。如果您真的想快速解决问题,或者根本想解决问题,请任何人再次帮助我...
  • 使用 Firebug,您可以尝试从生成的 HTML 中打开 CSS。尝试,并查看生成的路径。这将是错误的,你会发现如何;您可能需要在 styles/ 之前添加一个斜杠。

标签: css jsp struts2


【解决方案1】:

您应该将 .css 类型映射到 web.xml 文件中,如下所示!

<filter-mapping>
    <filter-name>expires-filter</filter-name>
    <url-pattern>*.css</url-pattern>
</filter-mapping>

【讨论】: