Spring Boot – JSP View Example

2018.05.03 15:46

졸리운_곰 조회 수:137

 

Spring Boot – JSP View Example

Learn to create and configure spring boot application which uses JSP template files to render view layer. It uses embedded Tomcat server to run the application.

Sourcecode Structure

The files in this application are placed as given structure in image.

Spring Boot Application Structure
Spring Boot Application Structure

Maven dependencies – pom.xml

This application uses given below dependencies.

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.howtodoinjava</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Tomcat Embed -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- To compile JSP files -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Spring Boot Application Initializer

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure() method. This makes use of Spring Framework’s Servlet 3.0 support and allows you to configure your application when it’s launched by the servlet container.

package com.howtodoinjava.app.controller;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
 
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {
 
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootWebApplication.class);
    }
 
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

Spring Controller

Controller classes can have methods mapped to specific URLs in the application. In given application, it has two views i.e. “/” and “/next”.

package com.howtodoinjava.app.controller;
 
import java.util.Map;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class IndexController {
 
    @RequestMapping("/")
    public String home(Map<String, Object> model) {
        model.put("message", "HowToDoInJava Reader !!");
        return "index";
    }
     
    @RequestMapping("/next")
    public String next(Map<String, Object> model) {
        model.put("message", "You are in new page !!");
        return "next";
    }
 
}

Configure JSP View Resolver

To resolve JSP files location, you can have two approaches.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

1) Add entries in application.properties

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
 
//For detailed logging during development
 
logging.level.org.springframework=TRACE
logging.level.com=TRACE

2) Configure InternalResourceViewResolver

package com.howtodoinjava.app.controller;
 
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.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }
}

JSP Files

Two used JSP files in this spring boot jsp example – are below.

index.jsp

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
    <div>
        <div>
            <h1>Spring Boot JSP Example</h1>
            <h2>Hello ${message}</h2>
             
            Click on this <strong><a href="next">link</a></strong> to visit another page.
        </div>
    </div>
</body>
</html>

next.jsp

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
    <div>
        <div>
            <h1>Another page</h1>
            <h2>Hello ${message}</h2>
             
            Click on this <strong><a href="/">link</a></strong> to visit previous page.
        </div>
    </div>
</body>
</html>

Run the application

After whole code is written and placed inside folders, run the application by executing main() method in SpringBootWebApplication class.

Now hit the URL: http://localhost:8080/

Spring Boot Application - index
Spring Boot Application – index

Click next link

Spring Boot Application - next
Spring Boot Application – next

Spring Boot JSP example Source Code

 

[출처] https://howtodoinjava.com/spring/spring-boot/spring-boot-jsp-view-example/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
126 Creating a CRUD REST API/Service with Spring Boot, JPA and Hibernate file 졸리운_곰 2018.08.17 147
125 Spring boot에서 REST API 개발 시작해보기 file 졸리운_곰 2018.08.17 350
124 [JSP] 네이버 스마트 에디터 연동 + 이미지파일 업로드 기능 추가 file 졸리운_곰 2018.07.28 1123
123 Use React and Spring Boot to Build a Simple CRUD App file 졸리운_곰 2018.07.28 385
122 JSP CRUD Example jsp 기본예제 file 졸리운_곰 2018.07.28 166
121 스웨거 2.0으로 스프링 부트 어플리케이션 API 문서화하기 file 졸리운_곰 2018.05.24 132
120 Spring REST API 문서를 Swagger로 만들자 file 졸리운_곰 2018.05.22 411
119 Spring REST API에 Swagger 2 설정하기 file 졸리운_곰 2018.05.22 335
118 Spring Boot와 AngualrJS를 조합한 코드 자동 생성 도구(scaffolding) file 졸리운_곰 2018.05.17 141
117 Spring java Code 기반 설정 Configuration 어노테이션과 Bean 어노테이션 졸리운_곰 2018.05.14 77
116 java spring redis 세션 공유 : Spring Session을 이용한 세션 클러스터링 졸리운_곰 2018.05.06 1041
115 Spring MVC hello world example file 졸리운_곰 2018.05.04 223
114 Create a Web Application With Spring Boot file 졸리운_곰 2018.05.03 142
113 Spring Boot and JSP Tutorial file 졸리운_곰 2018.05.03 427
112 Spring Boot Hello World Example – JSP file 졸리운_곰 2018.05.03 109
» Spring Boot – JSP View Example file 졸리운_곰 2018.05.03 137
110 SpringMVC-JSP 프로젝트를 Spring Boot로 옮기기 file 졸리운_곰 2018.05.03 319
109 SPRING BOOT에서 JSP 사용하기 졸리운_곰 2018.05.03 65
108 MYBATIS 기본 - SELECTLIST file 졸리운_곰 2018.03.26 79
107 Spring MVC 에 MyBatis 적용해 보기. file 졸리운_곰 2018.03.26 94
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED