Development Tip

Spring에서 .html 파일을 제공하는 방법

yourdevel 2020. 11. 17. 21:12
반응형

Spring에서 .html 파일을 제공하는 방법


Spring으로 웹 사이트를 개발 중이며 .jsp 파일 (예 : .html)이 아닌 리소스를 제공하려고합니다.

지금은 내 서블릿 구성의이 부분을 주석 처리했습니다.

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

그리고 컨트롤러에서 리소스에 대한 전체 경로를 반환하려고했습니다.

@Controller
public class LandingPageController {

protected static Logger logger = Logger.getLogger(LandingPageController.class);

@RequestMapping({"/","/home"})
public String showHomePage(Map<String, Object> model) {
    return "/WEB-INF/jsp/index.html";   
   }
}

index.html 파일이 해당 폴더에 있습니다.

참고 : index.html을 index.jsp로 변경하면 이제 서버가 페이지를 올바르게 제공합니다.

감사합니다.


초기 문제는 구성이 속성을 지정 suffix=".jsp"하므로 ViewResolver 구현 클래스가 .jsp메서드에서 반환되는 뷰 이름 끝에 추가 된다는 입니다.

그러나 InternalResourceViewResolver그때 주석을 달았 기 때문에 나머지 애플리케이션 구성에 따라 다른 ViewResolver가 등록되지 않았을 수 있습니다. 지금은 아무것도 작동하지 않는다는 것을 알 수 있습니다.

이후 .html파일은 정적 및 서블릿에 의해 처리가 필요하지 않습니다 다음은 사용하는 것이 더 효율적이며 간단 <mvc:resources/>매핑 . 이것은 Spring 3.0.4+가 필요합니다.

예를 들면 :

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

이는 것 통과 로 시작하는 모든 요청을 /static/받는 webapp/static/디렉토리.

그래서 넣어 index.htmlwebapp/static/하고 사용하여 return "static/index.html";당신의 방법에서, 봄은보기를 찾아야한다.


서블릿 구성 파일에서 view-controller 태그 (Spring 3)를 사용할 수 있으므로 컨트롤러 메서드를 구현할 필요가 없다고 덧붙였습니다.

<mvc:view-controller path="/" view-name="/WEB-INF/jsp/index.html"/>

문제의 배경

가장 먼저 이해해야 할 것은 다음과 같습니다. jsp 파일을 렌더링하는 것은 스프링이 아닙니다. 그것을하는 것은 JspServlet (org.apache.jasper.servlet.JspServlet)입니다. 이 서블릿은 Spring이 아닌 Tomcat (재스퍼 컴파일러)과 함께 제공됩니다. 이 JspServlet은 jsp 페이지를 컴파일하는 방법과이를 html 텍스트로 클라이언트에 반환하는 방법을 알고 있습니다. tomcat의 JspServlet은 기본적으로 * .jsp 및 * .jspx의 두 가지 패턴과 일치하는 요청 만 처리합니다.

이제 봄이 InternalResourceView(또는 JstlView)로 뷰를 렌더링 할 때 실제로 세 가지가 발생합니다.

  1. 모델에서 모든 모델 매개 변수를 가져옵니다 (컨트롤러 핸들러 메서드에 의해 반환 됨 "public ModelAndView doSomething() { return new ModelAndView("home") }").
  2. 이러한 모델 매개 변수를 요청 속성으로 노출 (JspServlet에서 읽을 수 있도록)
  3. JspServlet에 요청을 전달합니다. RequestDispatcher각 * .jsp 요청이 JspServlet으로 전달되어야 함을 알고 있습니다 (이는 기본 tomcat의 구성이므로).

당신은 단순히 home.html을 바람둥이로보기 이름을 변경하면됩니다 하지 요청을 처리하는 방법을 알고있다. * .html 요청을 처리하는 서블릿이 없기 때문입니다.

해결책

이것을 해결하는 방법. 가장 분명한 세 가지 해결책이 있습니다.

  1. html을 리소스 파일로 노출
  2. * .html 요청도 처리하도록 JspServlet에 지시
  3. 자신의 서블릿을 작성하십시오 (또는 * .html에 대한 다른 기존 서블릿 요청에 전달).

이를 달성하는 방법에 대한 완전한 코드 예제는 다른 게시물의 내 ​​답변을 참조하십시오 : Spring MVC에서 요청을 HTML 파일에 매핑하는 방법?


동일한 View 해석기를 계속 사용할 수 있지만 접미사를 비워 둘 수 있습니다.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
    p:prefix="/WEB-INF/jsp/" p:suffix="" />

이제 코드는 아래 샘플과 같이 index.html 또는 index.jsp를 반환하도록 선택할 수 있습니다.

@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
    return "/test.jsp";
}

@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
    return "/test.html";
}   

나는 같은 문제에 직면하고 Spring MVC에서 html 페이지를로드하기 위해 다양한 솔루션을 시도했으며 다음 솔루션이 나를 위해 일했습니다.

서버의 web.xml에서 1 단계는이 두 줄을 주석으로 처리합니다.

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

2 단계 : 응용 프로그램의 웹 XML에 다음 코드를 입력합니다.

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

3 단계 : 정적 컨트롤러 클래스 만들기

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Spring 구성 파일의 4 단계에서 접미사를 .htm .htm으로 변경합니다.

5 단계 페이지 이름을 .htm 파일로 변경하고 WEB-INF에 저장하고 서버를 빌드 / 시작합니다.

localhost:8080/.../landingPage

html 파일에 대한 Java 구성 (이 경우 index.html) :

@Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/index.html").addResourceLocations("/index.html");
    }

}

change p:suffix=".jsp" value acordingly otherwise we can develope custom view resolver

http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/UrlBasedViewResolver.html


It sounds like you are trying to do something like this:

  • Static HTML views
  • Spring controllers serving AJAX

If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:

  1. Forward all .html, .css, .js, .png, etc requests to the webserver's resource handler
  2. Map all other requests to spring controllers

Here is one way to accomplish that...

web.xml - Map servlet to root (/)

<servlet>
            <servlet-name>sprung</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            ...
<servlet>

<servlet-mapping>
            <servlet-name>sprung</servlet-name>
            <url-pattern>/</url-pattern>
</servlet-mapping>

Spring JavaConfig

public class SpringSprungConfig extends DelegatingWebMvcConfiguration {

    // Delegate resource requests to default servlet
    @Bean
    protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
        DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
        return dsrh;
    }

    //map static resources by extension
    @Bean
    public SimpleUrlHandlerMapping resourceServletMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

        //make sure static resources are mapped first since we are using
        //a slightly different approach
        mapping.setOrder(0);
        Properties urlProperties = new Properties();
        urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
        mapping.setMappings(urlProperties);
        return mapping;
    }

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();

        //controller mappings must be evaluated after the static resource requests
        handlerMapping.setOrder(1);
        handlerMapping.setInterceptors(this.getInterceptors());
        handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setUseSuffixPatternMatch(false);
        //set other options here
        return handlerMapping;
    }
}

Additional Considerations

  • Hide .html extension - This is outside the scope of Spring if you are delegating the static resource requests. Look into a URL rewriting filter.
  • Templating - You don't want to duplicate markup in every single HTML page for common elements. This likely can't be done on the server if serving HTML as a static resource. Look into a client-side *VC framework. I'm fan of YUI which has numerous templating mechanisms including Handlebars.

참고URL : https://stackoverflow.com/questions/15479213/how-to-serve-html-files-with-spring

반응형