Spring 3 MVC и Tiles 2 - не могут отображать статические ресурсы, когда у контроллера @RequestMapping есть шаблон URI - PullRequest
2 голосов
/ 08 октября 2011

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

CSS и изображения не отображаются в виде плитки, возвращаемом методом обработчика контроллера "displayPropertyPage", у которого @RequestMapping имеет шаблон URI (@RequestMapping (value = "/ getproperty / {propertyID}" *) 1004 *, method = RequestMethod.GET)).

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

Другие представления, возвращаемые методами обработчика контроллера с простым путем, таким как (@RequestMapping (value = "/ propertylistings", method = RequestMethod.GET)), отображают все статические ресурсы, включая 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 обработчика.

Изображения находятся в папке 'images-homes'.

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

  • ЦСИ
    • основной
      • WebApp
        • ресурсы
          • фото-дом
          • 1036 * 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 Ответ

2 голосов
/ 08 октября 2011

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

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'/>"/>
...