2016-08-12 8 views
0

У меня есть приложение Spring MVC с кучей * .css, * .js и * .png файлы в настоящее время помещены в SRC/основной/Java/ресурсы/ каталог. Я прочитал «Весенние документы» и некоторые учебные пособия о том, как загрузить эти файлы для своих шаблонов, используя класс ResourceHandlerRegistry, но это не работает для меня.JSP, импорт CSS, JS, изображения

Мои WebConfig (что расширяет WebMvcConfigurerAdapter):

package by.vk.arteziowebapp.configuration.webConfiguration; 
 

 
import org.springframework.context.MessageSource; 
 
import org.springframework.context.annotation.Bean; 
 
import org.springframework.context.annotation.ComponentScan; 
 
import org.springframework.context.annotation.Configuration; 
 
import org.springframework.context.annotation.PropertySource; 
 
import org.springframework.context.support.ReloadableResourceBundleMessageSource; 
 
import org.springframework.web.servlet.LocaleResolver; 
 
import org.springframework.web.servlet.ViewResolver; 
 
import org.springframework.web.servlet.config.annotation.*; 
 
import org.springframework.web.servlet.i18n.CookieLocaleResolver; 
 
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; 
 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 
 

 
import java.util.Locale; 
 

 
/** 
 
* The WebConfig.class. 
 
* Purpose: Web configuration. 
 
* 
 
* @author Vadzim Kavalkou 
 
* @version 1.0 22/07/2016 
 
*/ 
 
@Configuration 
 
@EnableWebMvc 
 
@ComponentScan({"by.vk.arteziowebapp.web", "by.vk.arteziowebapp.configuration.*"}) 
 
@PropertySource("classpath:i18n") 
 
public class WebConfig extends WebMvcConfigurerAdapter { 
 

 
    /** 
 
    * Gets viewResolver with properties. 
 
    * 
 
    * @return viewResolver. 
 
    */ 
 
    @Bean 
 
    public ViewResolver viewResolver() { 
 
     InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
 
     viewResolver.setPrefix("/WEB-INF/views/"); 
 
     viewResolver.setSuffix(".jsp"); 
 
     viewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class); 
 
     /*Set whether to make all Spring beans in the application context accessible 
 
     as request attributes, through lazy checking once an attribute gets accessed.*/ 
 
     viewResolver.setExposeContextBeansAsAttributes(true); 
 
     return viewResolver; 
 
    } 
 

 
    /** 
 
    * Sets the path to css,image and js files. 
 
    * 
 
    * @param registry 
 
    */ 
 
    @Override 
 
    public void addResourceHandlers(final ResourceHandlerRegistry registry) { 
 
     registry 
 
       .addResourceHandler("/resources/**") 
 
       .addResourceLocations("/resources/") 
 
       .setCachePeriod(31556926); 
 
    } 
 

 
    /** 
 
    * DispatcherServlet forwards requests for static resources to the servlet container’s default servlet 
 
    * and not tries to handle them itself. 
 
    * 
 
    * @param configurer . 
 
    */ 
 
    @Override 
 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
 
     configurer.enable(); 
 
    } 
 

 
    /** 
 
    * Gets messageSource with locales description. 
 
    * 
 
    * @return messageSource. 
 
    */ 
 
    @Bean 
 
    public MessageSource messageSource() { 
 
     ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
 
     messageSource.setBasename("classpath:i18n/messages"); 
 
     messageSource.setDefaultEncoding("UTF-8"); 
 
     return messageSource; 
 
    } 
 

 
    /** 
 
    * Gets LocaleResolver object with locale's properties. 
 
    * 
 
    * @return resolver. 
 
    */ 
 
    @Bean(name = "localeResolver") 
 
    public LocaleResolver localeResolver() { 
 
     CookieLocaleResolver resolver = new CookieLocaleResolver(); 
 
     resolver.setDefaultLocale(new Locale("en")); 
 
     resolver.setCookieName("localCookie"); 
 
     resolver.setCookieMaxAge(3600); 
 
     return resolver; 
 
    } 
 

 
    /** 
 
    * Sets LocaleInterceptors parameters. 
 
    * 
 
    * @param registry 
 
    */ 
 
    @Override 
 
    public void addInterceptors(InterceptorRegistry registry) { 
 
     LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); 
 
     interceptor.setParamName("locale"); 
 
     registry.addInterceptor(interceptor); 
 
    } 
 
}

Мой index.jsp: (SRC/главная/веб-приложение/WEB-INF/вид /)

<%@ page language="java" contentType="text/html" %> 
 
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
 

 
<c:url value="/index?locale=ru" var="localeRU"/> 
 
<c:url value="/index?locale=en" var="localeEN"/> 
 

 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 

 
<head> 
 
    <title><spring:message code="label.titleIndex"/></title> 
 

 
    <spring:url value="/resources/css/style.css" var="css"/> 
 
    <spring:url value="/resources/js/script.js" var="js"/> 
 
    <spring:url value="/resources/js/jquery-2.2.1.min.js" var="jq"/> 
 
    <spring:url value="/resources/images/vk.png" var="vk"/> 
 
    <spring:url value="/resources/images/vk-mouseover.png" var="vkMouseOver"/> 
 

 
    <link href="${css}" rel="stylesheet"/> 
 

 
</head> 
 

 
<body> 
 

 
<c:if test="${param.logout != null}"> 
 
    <p> 
 
     <spring:message code="label.logoutMessage"/> 
 
    </p> 
 
</c:if> 
 

 
<div id="locales"><a href="${localeRU}">RU</a> | <a href="${localeEN}">EN</a></div> 
 

 
<form:form action='/result' method='get' id="loginForm"> 
 

 
    <h1><spring:message code="label.titleIndex"/></h1> 
 

 
    <fieldset id="inputs"> 
 
     <input id="email" type='text' placeholder="<spring:message code="label.email"/>"/> 
 
     <input id="password" type="password" placeholder="<spring:message code="label.password"/>"/> 
 
    </fieldset> 
 

 
    <input type="submit" id="submit" value="<spring:message code="label.loginButton"/>"/> 
 

 
    <input type="hidden" 
 
      name="${_csrf.parameterName}" 
 
      value="${_csrf.token}"/> 
 
</form:form> 
 

 
<footer id="footer"> 
 
    <div id="footer-info">&copy VK, 2015-</div> 
 
    <div id="image-ref"> 
 
     <a href="http://vk.com/"><img id="vk-image" src="${vk}"></a> 
 
    </div> 
 
</footer> 
 

 
<script src="${js}" rel="script"/> 
 
<script src="${jq}" rel="script"/> 
 

 
</body> 
 

 
</html>

Спасибо, товарищи!

ответ

0

Переместите файлы из src/main/java/resources в src/main/resources и удалите часть «/ resources» в конфигурацию пружины, например.

<spring:url value="/css/style.css" var="css"/> 

Maven будет размещать файлы в каталоге ресурсов в корне classpass, а не в папку/ресурсов в корне классам.

+0

Было ли это, как вы сказали, ничего не изменилось :( [link] (http://hkar.ru/KhYV) –

+0

Я проверил свой * .war файл, и я не нашел здесь папку ресурсов. inf и meta-inf ... –

+0

не должна быть папкой ресурсов на войне. Эти файлы должны быть в папке верхнего уровня войны. Переместите каталоги css, js и images в папку webapp. Затем она должна работать – Guenther

Смежные вопросы