Spring и тегируют ресурсы mvc, не могут получить доступ к файлам .css и .js - PullRequest
2 голосов
/ 29 марта 2012

Мое приложение использует Spring 3.0.4 (это первая версия, в которой тег mvc: resources работает нормально).В настоящее время проблема заключается в том, что мое приложение не может получить доступ к файлам .css и .js из сопоставленных ресурсов.

Структура test.war:

/test -root
   |
   /static-resource
            |
            /css
               |
               /screen.css
            |
            /js
   |
   /WEB-INF
   |
   /index.jsp

Мой test-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

        <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/static-resource/"/>

    <context:annotation-config/>
    <context:component-scan base-package="org.web"/>
    <tx:annotation-driven/>

        <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
            <property name="definitions">
                <list>
                    <value>/WEB-INF/tiles-defs.xml</value>
                </list>
            </property>
        </bean>

        <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
        </bean>

 <bean id="authenticationInterceptor" class="org.util.AuthenticationInterceptor"/>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="cacheSeconds" value="-1"/>
    </bean>

    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en"/>
        <property name="cookieName" value="bovalta_language"/>
    </bean>

    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="authenticationInterceptor"/>
            <ref bean="localeChangeInterceptor"/>
       </list>
   </property>
    </bean>



</beans>

В index.jsp я пытаюсь получить доступ к ресурсам двумя способами с помощью URL-адреса пружины и URL-адреса JSTL, как показано ниже

<%-- With JSTL url --%>
<link media="screen" rel="stylesheet" href="<c:url value="/resources/css/screen.css"/>" type="text/css"/>
<%-- With Spring url --%>
<spring:url value="/resources" var="resourceUrl"/>
<link media="screen" rel="stylesheet" href="${resourceUrl}/css/screen.css" type="text/css" />

Когда я удаляю файл war в Tomcat AS, приложение работаетнормально без каких-либо исключений, но сервер Tomcat не может найти мои css и js файлы из ресурсов.Я пытаюсь добраться до файла css через URL http://localhost:8080/test/resources/css/screen.css, но Tomcat не нашел его.Любое предложение будет полезно.

Заранее спасибо

Ответы [ 3 ]

7 голосов
/ 30 марта 2012

FYI

Для всех, кто столкнулся бы с той же проблемой, что и я, я решил свою проблему и поделился с вами:

test-servlet.xml такой же без изменений, как в моем предыдущем посте.

  <mvc:annotation-driven/>
  <mvc:resources mapping="/resources/**" location="/static-resource/"/>

на странице index.jsp будет выглядеть следующим образом:

<spring:url value="/resources/css/screen.css" var="resourceUrl"/>
<link media="screen" rel="stylesheet" href="${resourceUrl}" type="text/css" />

Основная проблема была в моем файле web.xml, поскольку я сопоставил весенний сервлет с

<url-pattern>/*.htm</url-pattern>

вместо этого вы должны отображать только

<url-pattern>/</url-pattern>

web.xml будет выглядеть так:

    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

Спасибо за все!

1 голос
/ 14 ноября 2013

Я столкнулся с той же проблемой, и вот как я решил проблему: Весной конфигурационный файл Заменить

<mvc:resources mapping="/resources/**" location="/resources/"/>
With
<mvc:default-servlet-handler/>

И укажите следующий путь в JSP для загрузки статического содержимого

<link rel="stylesheet" href="resources/css/Mass.css" type="text/css"/>

Надеюсь, это поможет!

0 голосов
/ 27 марта 2017

тест-servlet.xml

    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"></mvc:resources>

<link href="<c:url value="../resources/css/style.css" />" rel="stylesheet">
...