문제

My Maven Spring 프로젝트 디렉토리 구조는 아래와 같습니다. 나는 Spring-4 주석 기반 구성을 사용하고 있습니다. 아래와 같이 리소스를 구성합니다. 나는 많은 stackoverflow 질문 및 다른 웹 사이트에서 제안 된 여러 가지 방법을 시도했습니다

스프링 4 정적 자원로드

http://imwill.com/ Spring-MVC-4-add-static-resources-innotation / #. u5gzlxks9i4

그러나 JSP 파일은 리소스를로드 할 수 없으며 모든 정적 콘텐츠 요청은 404 오류를 반환합니다. 나는 JSP에서 이러한 것을 시도했다.

 <link href="resources/css/bootstrap.css" rel="stylesheet" media="screen">
 <link href="/resources/css/bootstrap.css" rel="stylesheet" media="screen">
 <link href="css/bootstrap.css" rel="stylesheet" media="screen">
.

편집 : 이제는 JBoss 5에서 더 높은 버전으로 프로젝트를 업그레이드 할 수 없기 때문에 Servlet 2.5를 사용하고 있습니다. JBoss5는 서블릿 3을 지원하지 않으며 해당 문제가됩니까?

@Configuration
@ComponentScan("com.mgage.mvoice")
public class MyAppWebConfig extends WebMvcConfigurerAdapter {
     public void addResourceHandlers(ResourceHandlerRegistry registry) {  
        // I tried these many combinations separately.

        ResourceHandlerRegistration resourceRegistration = registry
            .addResourceHandler("resources/**");
        resourceRegistration.addResourceLocations("/resources/**");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/**");
        registry.addResourceHandler("/img/**").addResourceLocations("/img/**");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/**");
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("classpath:/resources/"); 
              // do the classpath works with the directory under webapp?
     }

}
.

프로젝트 구조

도움이 되었습니까?

해결책

이 작업

   registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
.

및 JSP 파일에서

와 같은 정적 리소스를 참조합니다.
<link href="resources/css/bootstrap.css" rel="stylesheet" media="screen">
.

다른 팁

나는 그것이 조금 늦었습니다. 그러나 나는 최근에 비슷한 문제로 직면 해있었습니다. 레슬링의 며칠 후에 마침내 DispatcherServlet이 요청을 처리하도록 구성되어 있지 않으므로 자원이 결코 보이지 않았습니다. 그래서 나는 다른 사람들 이이 답변을 유용하게 찾을 수 있기를 바랍니다.

위의 구성 클래스를 제공하는 Dispatcher 서블릿이 루트 ( "/")가 아니라 맨 위 워드 (예 : "/ data /")로 매핑 된 경우 동일한 문제로 직면 할 수 있습니다. < / P>

내 디스패처 서블릿에 대해 "/ data / *"로 매핑이 있다고 가정합니다. 그래서 내 전화가

처럼 보입니다
http://localhost:8080/myWebAppContext/data/command
.

그리고 나는 자원 매핑을 가진 것으로 생각된다고 생각했다. "/ content / ** / *", 그런 다음

로 액세스 할 수 있습니다.
http://localhost:8080/myWebAppContent/content/resourcePath
.

하지만 사실이 아닙니다.

를 사용해야합니다.
http://localhost:8080/myWebAppContent/data/content/resourcePath
. 대신

. 이것은 분명하지 않았으며 대부분의 샘플의 대부분이 디스패처 서블릿의 매핑을 위해 루트 "/"를 사용하기 때문에 문제가되지 않았습니다. 나중에 고려하면 DispatcherServlet이 호출을 평가해야하며 리소스 핸들러가 "컨트롤러"라는 서블릿에 대한 콘텐츠 / 알림이 이전에 알고 있어야합니다.

그러나 나머지 서비스 (angularjs)에서 데이터 (REST 서비스를 통해) 또는 콘텐츠 (일반 텍스트를 반환)할지 여부를 확인하고 싶습니다. 데이터는 데이터베이스에서 제공되지만 콘텐츠는 파일 (예 : PDF Docs)에서 제공됩니다. 따라서 Dispatcher 서블릿에 두 개의 매핑을 추가하기로 결정했습니다.

public class MidtierWebConfig implements WebApplicationInitializer {

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

    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(MidtierAppConfig.class);

    servletContext.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(MidtierDispatcherConfig.class);

    Dynamic netskolaDispatcher = servletContext.addServlet(
        "dispatcher",
        new DispatcherServlet(dispatcherContext)
    );
    netskolaDispatcher.setLoadOnStartup(1);
    netskolaDispatcher.addMapping("/data/*");
    netskolaDispatcher.addMapping("/content/*");
}

}
.

MIDTIERAPPCONFIG 클래스는 비어 있지만 MIDTIERDISPATCHERCONFIG는 정적 리소스를 정의합니다.

@Configuration
@ComponentScan("my.root.package")
@EnableWebMvc
public class MidtierDispatcherConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
            .addResourceHandler("/courses/**/*")
            .addResourceLocations("/WEB-INF/classes/content/")
        ;
    }
}
.

이제 @ 컨트롤러의 액세스를 원할 때 / data / prefix를 사용하고 내 리소스에 액세스하려는 경우 / content / prefix를 사용합니다. @RequestMapping ( "/ about") 메소드가있는 @RequestMapping 클래스가있는 @RequestMapping ( "/ app") 클래스가있는 경우 데이터 / 앱 / 정보 및 콘텐츠 / 앱 / 정보가 해당 방법으로 호출됩니다. 실제로 Dispatcher가 "data /"및 "content /")를 모두 실업하고 나머지 URL ( "app / about") 만 해석하기 때문에 실제로 나는 / app / courses / whatweedprate를 사용하고 있습니다. "두 경우 모두)에 적절한 @Controller를 찾으려면

에 관계없이 내가 도달 한 현재의 솔루션은 나를 위해 충분히 만족 스럽기 때문에, 나는 그것이 그대로 남겨 둘 것입니다.

이것은 나를 위해 일했습니다./resources/js/select.js에서 사용할 수있는 파일.@EnableWebMvc 주석이 누락되지 않았 음을 조심하십시오.

@EnableWebMvc
@EnableTransactionManagement
public class ApplicationContextConfig extends WebMvcConfigurerAdapter {

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

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

웹 페이지의 URI를 단순화 할 수 있습니다. 자원의 파일 이름을 포함 할 수 있습니다. <link href="bootstrap.css" rel="stylesheet" media="screen">
적절한 구성이 다음과 같을 수 있습니다.

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

Spring은 URI에서 추출 된 파일 이름을 가진 '/ Resources / CSS /'문자열을 연결하여 리소스의 실제 위치를 식별합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top