我不能在我的JSP页面中包含javaScript和css

I can not include javaScript and css to my JSP page

本文关键字:包含 javaScript css 不能 我的 JSP      更新时间:2023-09-26

我不能在我的JSP页面中包含javaScript和css字段。我试了这个和这个,但没有帮助。

我的JSP:

  <html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <script src="../resources/js/my.js"></script>
        <link rel="stylesheet" href="../resources/css/menu.css" />
...

和映射:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.springapp.mvc"/>
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="resources" cache-period="31556926"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

和ctructure:

WEB-INF
 -pages
   -my.jsp
 -resources
   -js
     -my.js
   -css
     -menu.css
 -mvc-dispatcher-servlet.xml
 -web.xml

新结构没有帮助

webapp- - -js-my.js但css-menu.css-WEB-INF页面-my.jsp-mvc-dispatcher-servlet.xmlweb . xml

我做错了什么?

将你的资源文件夹移出WEB-INF,并在下面添加你的like。

<script src="/resources/js/my.js"></script>
<link rel="stylesheet" href="/resources/css/menu.css" />

您不能通过相对路径引用WEB-INF文件夹中的资源,您已经提到过。

尝试:

<script src="${pageContext.request.contextPath}/resources/js/my.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/menu.css" />

您的JSP中有可用的标记库吗?

如果是这样,考虑如下:<script src="<c:url value="/js/my.js"/>"></script>

你的结构应该是:

webapp
  -WEB-INF
    -mvc-dispatcher-servlet.xml
    -web.xml
    -pages
      -my.jsp
  -resources
    -js
     -my.js
    -css
     -menu.css

使静态资源不在WEB-INF下。<mvc:resources>标签告诉spring根本不提供这些url,将它们留给servlet容器(Tomcat等)来提供。但是Tomcat等不会直接从WEB-INF目录提供内容。

编辑
<mvc:resources mapping="/resources/**"
               location="/"
               cache-period="31556926" />

假设您的项目使用标准目录布局,将Javascript放在:src/main/webapp/js/my.js下,然后使用相对URL /resources/js/my.js访问它们。