Подтвердить что ты не робот

Как использовать тег spring MVC <mvc: resources> в контексте приложения java?

Я создал "на данный момент" простое и основное веб-приложение spring. Я использую дескриптор развертывания как простой файл web.xml, а затем контекст приложения как XML файл.

Хотя, теперь я хотел попытаться создать все мое веб-приложение spring, используя только java файлы. Поэтому я создал свой WebApplicationInitializer вместо обычного дескриптора развертывания и свой контекст приложения, который использует аннотацию @Configuration.

Дескриптор развертывания

package dk.chakula.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
 *
 * @author martin
 * @since 12-1-2012
 * @version 1.0
 */
public class Initializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        registerDispatcherServlet(servletContext);
    }

    private void registerDispatcherServlet(final ServletContext servletContext) {
        WebApplicationContext dispatcherContext = createContext(ChakulaWebConfigurationContext.class);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
        Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private WebApplicationContext createContext(final Class<?>... annotatedClasses) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(annotatedClasses);
        return context;
    }

} //End of class Initializer

Контекст приложения

package dk.chakula.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;

/**
 *
 * @author martin
 * @since 12-01-2013
 * @version 1.0
 */
@Configuration
@EnableWebMvc
@ComponentScan("dk.chakula.web")
public class ChakulaWebConfigurationContext {

    @Bean
    public TilesConfigurer setupTilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();
        String[] definitions = {"/layout/layout.xml"};
        configurer.setDefinitions(definitions);
        return configurer;
    }

    @Bean
    public UrlBasedViewResolver setupTilesViewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

} //End of class ChakulaWebConfigurationContext

Моя проблема в том, что я не могу найти способ "изолировать" мое сопоставление с папкой ресурсов, которая содержит изображения, css javascript и т.д. Когда мой контекст приложения находится в java.

В обычном контексте приложения XML я использовал этот тег, чтобы изолировать отображение в /resources/

<mvc:resources mapping="/resources/**" location="/resources/" />

Как я могу это сделать, поэтому мое веб-приложение может использовать мои изображения, css и т.д.

4b9b3361

Ответ 1

Чтобы иметь возможность обслуживать статические ресурсы в приложении Spring MVC, вам нужны два XML-тега: <mvc:resources/> и <mvc:default-servlet-handler/>. То же самое в конфигурации на основе Java Spring будет:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    // equivalents for <mvc:resources/> tags
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
    }

    // equivalent for <mvc:default-servlet-handler/> tag
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    // ... other stuff ...
}

Обратите внимание, что поскольку используется аннотация @EnableWebMvc, нет необходимости в расширении непосредственно WebMvcConfigurationSupport, и вы должны просто расширить WebMvcConfigurerAdapter. Подробнее см. JavaDoc для @EnableWebMvc.

Ответ 2

После использования часов в Интернете, читающих о Spring MVC 3, используя только java файлы, я упал на некоторые статьи, которые использовали подход, расширяя его из класса WebMvcConfigurationSupport, а затем переопределяя 2 метода - addResourceHandler (ResourceHandlerRegistry) и ResourceHandlerMapping().

Теперь мой новый контекст приложения выглядит следующим образом.

package dk.chakula.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;

/**
 *
 * @author martin
 * @since 12-01-2013
 * @version 1.0
 */
@Configuration
@EnableWebMvc
@ComponentScan("dk.chakula.web")
public class ChakulaWebConfigurationContext extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    @Bean
    public HandlerMapping resourceHandlerMapping() {
        AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) super.resourceHandlerMapping();
        handlerMapping.setOrder(-1);
        return handlerMapping;
    }

    @Bean
    public TilesConfigurer setupTilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();
        String[] definitions = {"/layout/layout.xml"};
        configurer.setDefinitions(definitions);
        return configurer;
    }

    @Bean
    public UrlBasedViewResolver setupTilesViewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

} //End of class ChakulaWebConfigurationContext

Как я понял, нам пришлось переопределить addResourceHandler, чтобы добавить местоположение и сопоставление ресурсов в реестр. После этого нам понадобился bean, который возвратил объект HandlerMapping. Порядок этого HandlerMapping должен быть установлен в -1, поскольку, поскольку я мог читать из документации Spring, тогда -1 означает

HandlerMapping упорядочен в Integer.MAX_VALUE-1 для обслуживания статических запросы ресурсов.

Мое приложение теперь может загружать css файлы и изображения в свои представления, и я хотел бы рассказать вам другим о том, чтобы ответить на этот вопрос, поэтому люди в будущем могли бы воспользоваться этим.

Ответ 3

Попробуйте следующее:

@Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }