본문 바로가기
JAVA/SPRING

[Spring]Spring Boot + Tiles

by F.E.D 2018. 4. 10.

1.Tiles란?


웹 페이지 상단이나 하단, 메뉴와 같은 반복적으로 사용되는 부분들에 대한 정보를 한 곳에 모아둔 프레임워크라고 합니다.

화면을 구성하는데 있어서 하나의 파일이 아닌 여러부분을 따로 작업해서 하나로 묶어 화면에 보여주는 것이라고 표현하기도 합니다. 

인클루드의 확장적 개념이라고 보면 더 이해가 쉬울 것 같습니다.

jsp include와 차이를 말한다면 jsp는 페이지 내에 동일한 레이아웃의 정보가 들어갑니다.

따라서, 전체적인 레이아웃을 변경하게 될 경우 모든 페이지를 수정해야합니다.

예를 들어, include는 include 파일 명이 바뀌면 모든 파일을 열어 include 파일명을 수정해주어야 합니다.

하지만 tiles는 보다 간편하게 설정파일로써 대응 할 수 있습니다.


* 기본 용어

Template : 페이지 레이아웃을 의미합니다. 

Attribute : Template의 빈 공간을 채우기 위해 사용 되는 정보입니다. 총 3가지 타입으로 구성 할 수 있습니다.
  • string : 문자열
  • template : 템플릿 내에 또 다른 레이아웃
  • definition : 전체 또는 일부 Attribute 들이 실제 내용으로 채워진 페이지

Definition : 사용자에게 제공 위하여 렌더링 되는 Template과 Attribute 연결할 수 있습니다.



2.실습


전체적인 디렉토리 모습입니다. 에러 페이지와 함께 구분 지어 화면을 띄워봅시다.




pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <!-- jstl -->
    <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
    </dependency>
    
    <!-- tomcat -->
    <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    
    <!-- tiles 추가 -->
    <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>3.0.8</version>
    </dependency>    
</dependencies>
cs


우선, Spring Starter Project 상에 WAR로 시작하여 프로젝트를 생성한 뒤에

pom.xml 에 jstl , tomcat, tiles 을 사용하기 위한 dependency 를 각각 추가해줍니다.


src/main/webapp/views/tiles/tiles.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
 
<tiles-definitions>
 
        <!-- base tiles layout add -->
 
        <definition name="base" template="/views/jsp/layout/base.jsp">
                <put-attribute name="header" value="/views/jsp/layout/header.jsp" />
                <put-attribute name="body" value="" />
                <put-attribute name="footer" value="/views/jsp/layout/footer.jsp" />
        </definition>
 
        <definition name="index" extends="base">
                <put-attribute name="body" value="/views/jsp/view/index.jsp" />
        </definition>
        
        <definition name="*/*" extends="base">
                <put-attribute name="body" value="/views/jsp/view/{1}/{2}.jsp" />
        </definition>
 
        <definition name="*/*/*" extends="base">
                <put-attribute name="body" value="/views/jsp/view/{1}/{2}/{3}.jsp" />
        </definition>
 
</tiles-definitions>
cs


tiles.xml 에 각각 레이아웃을 편성합니다.

base는 기본이 되는 템플릿 격인 레이아웃입니다.

그리고 기본 템플릿에 put-attribute로 header와 footer를 설정해뒀습니다.

이제 base를 확장시킨 index를 보면 각각의 header와 footer의 attribute로 추가된 레이아웃을 볼 수 있습니다.



src/main/webapp/views/jsp/error/404.jsp

src/main/webapp/views/jsp/error/500.jsp

1
2
<h1>404: Page not found</h1>
<h1>500: Internal server error</h1>

cs

혹시 에러날지 모르니 404.jsp, 500.jsp 를 각각 생성하여 에러페이지를 설정해줍니다.

error 폴더 내에 에러페이지를 생성하는 것만으로도 error page를 설정 할 수 있습니다. 

물론 error page 설정이 필요합니다.


src/main/resources/application.properties

1
2
#Error Page Setting
server.error.whitelabel.enabled=false
cs

기본 whitelabel 이라고 뜨는 errorpage를 커스텀으로 바꾸기 위해 설정값을 false로 해줍니다.



src/main/java/com/tiles/prac/config/ServerCustomize.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.tiles.prac.config;
 
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
 
public class ServerCustomize extends ServerProperties {
 
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        super.customize(container);
        container.addErrorPages(
                new ErrorPage(HttpStatus.NOT_FOUND, "/views/jsp/error/404.jsp"),
                new ErrorPage(HttpStatus.BAD_REQUEST, "/views/jsp/error/500.jsp"),
                new ErrorPage("/error")
        );
    }
}
 
 
cs


Override 어노테이션을 사용하여 errorpage를 설정해줍니다.


src/main/java/com/tiles/prac/config/TilesConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.tiles.prac.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;
 
@Configuration
public class TilesConfig {
 
    @Bean
    public UrlBasedViewResolver viewResolver() {
        UrlBasedViewResolver tilesViewResolver = new UrlBasedViewResolver();
        tilesViewResolver.setViewClass(TilesView.class);
        return tilesViewResolver;
    }
 
    @Bean
    public TilesConfigurer tilesConfigurer() {
 
        TilesConfigurer tiles = new TilesConfigurer();
        tiles.setDefinitions(new String[] { "/views/tiles/tiles.xml" });
        return tiles;
    }
}
 
 
cs


TilesConfig로 bean 상에 tiles view Resolver를 설정해줍니다.

더불어 tiles.xml 경로도 세팅해줍니다.


src/main/java/com/tiles/prac/controller/TilesController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.tiles.prac.controller;
 
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class TilesController {
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "index";
    }
 
}
cs


TilesController를 설정해주며 index 페이지로 들어갔을 시에 tiles.xml 에서 설정한 tiles 페이지가 뜨도록 합니다.



src/main/java/com/tiles/prac/controller/MyErrorController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.tiles.prac.controller;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class MyErrorController implements ErrorController {
 
    @Override
    public String getErrorPath() {
        return "/error";
    }
 
    @RequestMapping(value = "/error")
    Object error(HttpServletRequest request, HttpServletResponse response) {
        Map<StringString> err = new HashMap<>();
        err.put("my""custom error");
        return err;
    }
}
 
cs



마지막으로 tiles error 설정


이렇게 설정한 뒤에 


http://localhost:8080/index 로 들어가보시면 






수고하셨습니다 : )






출처 : 

http://jinhokwon.tistory.com/270

댓글