Spring Boot mvc with Jsp example

Datetime:2017-02-15 05:59:59         Topic: JSP          Share        Original >>
Here to See The Original Article!!!

This post is about integration of spring boot mvc with jsp .Here, we will be developing a spring MVC boot app in integration with jsp using spring controller.We will be using tomcat-embed-jasper artifact to render jsp.So let us start by defining our maven dependencies first.

Other Interesting Posts Spring MVC Angularjs Integration with complete JavaConfig Spring Hibernate Integration with complete JavaConfig Spring Junit Integration with complete JavaConfig Spring Ehcache Cacheable Example with complete javaConfig Spring Boot Thymeleaf Example Spring Boot Security Redirect after Login with complete JavaConfig Spring Security Hibernate Example with complete JavaConfig Securing REST API with Spring Security Basic Authentication Spring Security with Spring MVC Example Using Spring Boot Spring JMS Activemq Integration with Spring Boot Websocket spring Boot Integration with complete JavaConfig Maintaining Spring Session during Websocket Connection

Maven Dependencies

tomcat-embed-jasper : This is the artifact which is actually required to render .jsp pages in spring boot app.

All the other dependencies except tomcat-embed-jasper are common spring boot dependencies. pom.xml

<?xml version= "1.0" encoding= "UTF-8" ?> &ltproject xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd "> &ltmodelVersion> 4.0.0 </modelVersion> &ltgroupId> com.devglan </groupId> &ltartifactId> spring-boot-jsp-example </artifactId> &ltversion> 0.1.0 </version> &ltproperties> &lttomcat.version> 8.0.3 </tomcat.version> &ltstart-class> spring-boot-example.Application </start-class> </properties> &ltparent> &ltgroupId> org.springframework.boot </groupId> &ltartifactId> spring-boot-starter-parent </artifactId> &ltversion> 1.3.3.RELEASE </version> </parent> &ltdependencies> &ltdependency> &ltgroupId> org.springframework.boot </groupId> &ltartifactId> spring-boot-starter-web </artifactId> </dependency> &ltdependency> &ltgroupId> org.springframework.boot </groupId> &ltartifactId> spring-boot-starter-tomcat </artifactId> </dependency> &ltdependency> &ltgroupId> javax.servlet </groupId> &ltartifactId> jstl </artifactId> </dependency> &ltdependency> &ltgroupId> org.apache.tomcat.embed </groupId> &ltartifactId> tomcat-embed-jasper </artifactId> </dependency> </dependencies> </project>

Spring Bean Configuration

SpringBootServletInitializer enables process used in Servlet 3.0 using web.xml

EnableAutoConfiguration This will help apring boot to automatically identify how to configure Spring, based on the jar dependencies that we have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that we are developing a web application and setup Spring accordingly.


package com.devglan.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @ComponentScan (basePackages = "com.devglan" ) @Import ({BeanConfig. class , WebConfig. class }) @EnableAutoConfiguration public class Application extends SpringBootServletInitializer { private static Class applicationClass = Application. class ; public static void main(String[] args) { SpringApplication.run(Application. class , args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(applicationClass); } }

We have implemented WebApplicationInitializer.java to configure the ServletContext programmatically.


package com.devglan.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class ApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet( "dispatcher" , new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping( "/" ); } }


Defining this bean configuration is the main important part which will register the view resolver and also define the JstlView class.

package com.devglan.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration public class BeanConfig { @Bean public InternalResourceViewResolver setupViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix ( "/ui/jsp/" ); resolver.setSuffix ( ".jsp" ); resolver.setViewClass (JstlView.class); return resolver; } }

By default Spring Boot will serve static content from a directory called /static (or/publicor /resources or /META-INF/resources ) in the classpath or from the root of the ServletContext. But here we have defined out custom folder structure for static contents, hence it is required to tell Spring boot about how to render static content.


package com.devglan.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers( final ResourceHandlerRegistry registry) { registry.addResourceHandler( "/*.js/**" ).addResourceLocations( "/ui/static/" ); registry.addResourceHandler( "/*.css/**" ).addResourceLocations( "/ui/static/" ); } }

Following is the model class with getters and setters.


package com.devglan.model; public class User { private String name; private String address; private String email; public String getName() { return name; } public void setName(String name) { this .name = name; } public String getAddress() { return address; } public void setAddress(String address) { this .address = address; } public String getEmail() { return email; } public void setEmail(String email) { this .email = email; } }

Now let us define our controller that will serve the response to the client. Here we have hardcoded some user details.


package com.devglan.controller; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.devglan.model.User; @Controller public class DashboardController { @RequestMapping (value = "/welcome" , method = RequestMethod.GET) public ModelAndView welcome() { ModelAndView model = new ModelAndView(); model.setViewName( "welcome" ); return model; } @RequestMapping (value = "/dashboard" , method = RequestMethod.GET) public ModelAndView dashboard() { ModelAndView model = new ModelAndView(); model.addObject( "users" , getUsers()); model.setViewName( "dashboard" ); return model; } private List getUsers() { User user = new User(); user.setEmail( "johndoe123@gmail.com" ); user.setName( "John Doe" ); user.setAddress( "Bangalore, Karnataka" ); User user1 = new User(); user1.setEmail( "amitsingh@yahoo.com" ); user1.setName( "Amit Singh" ); user1.setAddress( "Chennai, Tamilnadu" ); User user2 = new User(); user2.setEmail( "bipulkumar@gmail.com" ); user2.setName( "Bipul Kumar" ); user2.setAddress( "Bangalore, Karnataka" ); User user3 = new User(); user3.setEmail( "prakashranjan@gmail.com" ); user3.setName( "Prakash Ranjan" ); user3.setAddress( "Chennai, Tamilnadu" ); return Arrays.asList(user, user1, user2, user3); } }

Client Side

Following is the welcome page which will be rendered for /welcome request


&lthtml> &lthead> &lttitle> Spring Boot Example</title> &ltlink href= "/bootstrap.min.css" rel="stylesheet"> &ltscript src= "/jquery-2.2.1.min.js" ></script> &ltscript src= "/bootstrap.min.js" ></script> </head> &ltbody> &ltdiv> &ltdiv class= "container" style= "margin:50px" > &ltdiv class= "row text-center" >&ltstrong> User Details</strong></div> &ltp&gtHello Friend, &lta href= "/dashboard" >&ltstrong&gtClick here</strong></a> to view the dashboard page.</p> </div> </div> </body> </html>

Now let us define our dashboard.jsp


<%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %> &lthtml> &lthead> &lttitle> Spring Boot Example</title> &ltlink href= "/bootstrap.min.css" rel="stylesheet"> &ltscript src= "/jquery-2.2.1.min.js" ></script> &ltscript src= "/bootstrap.min.js" ></script> </head> &ltbody> &ltdiv> &ltdiv class= "container" style= "margin:50px" > &ltdiv class= "row text-center" >&ltstrong> User Details</strong></div> &ltdiv class= "row" style= "border:1px solid green;padding:10px" > &ltdiv class= "col-md-4 text-center" >&ltstrong>Name</strong></div> &ltdiv class= "col-md-4 text-center" >&ltstrong&gtEmail</strong></div> &ltdiv class= "col-md-4 text-center" >&ltstrong>Address</strong></div> </div> &ltc:forEach var= "user" items= "${users}" > &ltdiv class= "row" style= "border:1px solid green;padding:10px" > &ltdiv class= "col-md-4 text-center" >${user.name}</div> &ltdiv class= "col-md-4 text-center" >${user.email}</div> &ltdiv class= "col-md-4 text-center" >${user.address}</div> </div> </c:forEach> </div> </div> </body> </html>

Run Application

1.Run Application.java as a java application.

2. Hit the url as http://localhost:8080/welcome .Following welcome.jsp page will be displayed.

3.Once you click on the link, dashboard.jsp will appear as below:


I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section .

References: Spring Framework References Spring Boot References