Spring 3 MVC и плитки 2 — не могут отображать статические ресурсы, когда controller @RequestMapping имеет шаблон URI

#spring #model-view-controller #tiles

#spring #модель-представление-контроллер #плитки

Вопрос:

Я использую Tiles 2, Spring 3 MVC, Tomcat версии 7 и Eclipse (набор инструментов Springsource). Я надеюсь, что кто-нибудь может помочь.

CSS и изображения не отображаются в виде плитки, который возвращается методом обработчика контроллера «displayPropertyPage», @RequestMapping которого имеет шаблон URI ( @RequestMapping(значение = «/ getproperty/{PropertyID}», метод = RequestMethod.ПОЛУЧИТЬ) ).

Я использую теги mvc:resources и mvc:default-servlet-handler, поэтому сервлет по умолчанию обслуживает запросы на статические ресурсы. Я также проверил html-скрипт, сгенерированный этим видом плитки, и в нем есть запись css.

Другие представления, возвращаемые методами обработчика контроллера с простым путем, таким как ( @RequestMapping(значение = «/ propertylistings», метод = RequestMethod .ПОЛУЧИТЬ) ) отображать все статические ресурсы, включая css, изображения и jquery, просто отлично.

Я заметил, что «информация о свойствах» пустой картинки в браузере имеет URL http://localhost:8080/realtyguide/getproperty/resources/images-homes/pic1.jpg когда это должно быть просто http://localhost:8080/realtyguide/resources/images-homes/pic1.jpg . URL-адрес выбирает путь «/ getproperty» из аннотации RequestMapping обработчика.

Изображения находятся в папке «изображения-дома».

Моя структура каталогов:

  • Src
    • Главная
      • веб-приложение
        • Ресурсы
          • изображения-дома
          • css
        • WEB-INF

Вот мой контроллер. Возвращаемое представление представляет собой определение плитки.

 @Controller
public class PropertyPageController {

    private MasterTableService masterTableService;

    @Autowired
    public PropertyPageController(MasterTableService masterTableService) {
        this.masterTableService = masterTableService;
    }

    @RequestMapping(value = "/getproperty/{propertyID}", method = RequestMethod.GET)
    public String displayPropertyPage(@PathVariable("propertyID") String propertyID, Model model) {

        model.addAttribute("mastertable", masterTableService.findByID(propertyID));

        return "propertyinfo.tiledef";
    }

}
  

Вот моя конфигурация сервлета приложения Spring:

 <?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:annotation-config />

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <context:component-scan base-package="com.springproject.realtyguide" />

    <!-- Enables the Spring MVC @Controller programming model -->    
    <mvc:annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
    <mvc:resources mapping="/resources/**" location="/resources/"/>   

    <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource requests to the container's default Servlet -->
    <mvc:default-servlet-handler/>      


    <!-- Bean to provide Internationalization  -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="WEB-INF/i18n/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="classpath:META-INF/spring/database.properties" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:META-INF/hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- __________ BEAN ENTRIES FOR TILES 2 -->

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

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" >
        <property name="order" value="0"/> 
        <property name="viewClass"> 
            <value>org.springframework.web.servlet.view.tiles2.TilesView </value>
        </property>
        <property name="requestContextAttribute" value="requestContext"/>
        <property name="viewNames" value="*.tiledef"/>
    </bean>

    <bean id="jstlViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="order" value="1"/> 
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix" value="/WEB-INF/views/"/> 
        <property name="suffix" value=".jsp"/> 
    </bean> 

    <!-- __________ END OF BEAN ENTRIES FOR TILES 2 -->

    <!-- Resolves localized <theme_name>.properties files in the classpath to allow for theme support -->
    <bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
        <property name="basenamePrefix" value="theme-" />
    </bean>

    <bean id="themeResolver" class="org.springframework.web.servlet.theme.CookieThemeResolver">  
        <property name="defaultThemeName" value="standard" />
    </bean>

</beans>
  

Вот мой web.xml:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Realty Guide</display-name>

      <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
      </context-param>

      <!-- Creates the Spring Container shared by all Servlets and Filters -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

      <!-- Handles Spring requests -->
      <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>

</web-app>
  

Я искал это в течение нескольких дней и не могу найти решение.

Спасибо за любую помощь, которую вы можете оказать.

Ответ №1:

Именно так вы ссылаетесь на свои ресурсы в своих представлениях. Если вы ссылаетесь на ресурс в своем представлении как:

 resources/images-homes/pic1.jpg
  

он будет добавлен к текущему URL-адресу контроллера. Если вы используете:

 /resources/images-homes/pic1.jpg
  

тогда он будет ссылаться на корень веб-сервера и не включать контекст вашего приложения, предполагая, что он не работает от имени root.

Вам необходимо изменить ссылки на ресурсы. Я предполагаю, что вы используете JSP для отображения представлений. Если это так, то используйте c:url из основной библиотеки JSTL, чтобы предоставить правильную ссылку на ваш ресурс:

перед

 <img src="resources/images-homes/pic1.jpg"/>
  

после

 <img src="<c:url value='/resources/images-homes/pic1.jpg'/>"/>
  

Комментарии:

1. Спасибо сканджо. Ваш совет по использованию c: url для изображения сработал отлично! Просто нужен еще один совет от вас. Мой css в моем файле jsp выглядит так: <link rel=»stylesheet» href=»<spring:theme code=’styleSheet’/>» type=»text/css» /> . Как я могу применить c:url к href с помощью spring:theme? Я действительно хотел бы сохранить темы в этом приложении.

2. Я понял. Я просто использовал c: set и c: url для темы. <c:set var="cssUrl"><spring:theme code='styleSheet'/></c:set> <link rel="stylesheet" type="text/css" href="<c:url value='${cssUrl}'/>" />