Partial Render View in Template in Spring MVC


On the Eclipse, create a Spring MVC project in Spring Boot

Enter Project Information:

  • Name: LearnSpringMVCWithRealApps
  • Group: com.demo
  • Artifact: LearnSpringMVCWithRealApps
  • Description: Learn Spring MVC with Real Apps
  • Package: com.demo

Select the technologies and libraries to be used:

  • Web

Click Next button to show Site Information for project

Click Finish button to finish create Spring MVC project

<?xml version="1.0" encoding="UTF-8"?>
<project 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">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.demo</groupId>
	<artifactId>LearnSpringMVCWithRealApps</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>LearnSpringMVCWithRealApps</name>
	<description>Learn Spring MVC with Real Apps</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- JSTL tag lib -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<!-- Tomcat for JSP rendering -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- Tiles -->
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-jsp</artifactId>
			<version>3.0.8</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-library</artifactId>
			<version>2.11.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>




spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

server.port=9596
package com.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
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 SpringMVCConfiguration extends WebMvcConfigurerAdapter {

	@Bean
	public UrlBasedViewResolver viewResolver() {
		UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
		urlBasedViewResolver.setViewClass(TilesView.class);
		return urlBasedViewResolver;
	}

	@Bean
	public TilesConfigurer tilesConfigurer() {
		TilesConfigurer tilesConfigurer = new TilesConfigurer();
		tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles/tiles.xml" });
		return tilesConfigurer;
	}
}

Create new package named com.demo.tags. In this package, create new java file named CategoryListTag.java. This file use create Custom Tag as below:

package com.demo.tags;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspWriter;
import org.springframework.web.servlet.tags.*;

public class CategoryListTag extends RequestContextAwareTag {

	@Override
	public void doFinally() {
		JspWriter writer = pageContext.getOut();
		try {
			List<String> categories = new ArrayList<String>();
			categories.add("Category 1");
			categories.add("Category 2");
			categories.add("Category 3");
			categories.add("Category 4");
			categories.add("Category 5");
			if (categories.size() > 0) {
				writer.print("<ul>");
				for (String category : categories) {
					writer.print("<li><a href=\"#\">" + category + "</a></li>");
				}
				writer.print("</ul>");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected int doStartTagInternal() throws Exception {
		return 0;
	}

}




Create new folder named tlds in src\main\webapp\WEB-INF folder. In this folder, create categoryTag.tld file as below:

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
	version="2.0">

	<tlib-version>1.0</tlib-version>
	<short-name>Category Tab Library</short-name>
	<uri>categoryTag</uri>

	<tag>
		<name>categoryiesList</name>
		<tag-class>com.demo.tags.CategoryListTag</tag-class>
		<body-content>empty</body-content>
	</tag>

</taglib>

Create new package named com.demo.controllers. In this package, create controllers as below:

Create new java class, named HomeController.java

package com.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("home")
public class HomeController {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "home.index";
	}

}

Create new java class, named AboutUsController.java

package com.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("aboutus")
public class AboutUsController {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "aboutus.index";
	}

}

Create new java class, named NewsController.java

package com.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("news")
public class NewsController {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "news.index";
	}

}




Create new folders with path webapp\WEB-INF\views in src\main. In views folder, create JSP Pages as below:

Create new folder named templates. Create new jsp file named mytemplate.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="category" uri="categoryTag" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Template</title>
<style type="text/css">
li {
	list-style-type: none;
}
</style>
</head>
<body>

	<table border="1" cellpadding="5" cellspacing="5" width="500">
		<tr>
			<td colspan="2">
				<a href="${pageContext.request.contextPath}/home">Home</a> |
				<a href="${pageContext.request.contextPath}/aboutus">About Us</a> |
				<a href="${pageContext.request.contextPath}/news">News</a>
			</td>
		</tr>
		<tr>
			<td valign="top" align="left" width="200">
				<category:categoryiesList/>
			</td>
			<td valign="top" align="left">
				<tiles:insertAttribute name="content"></tiles:insertAttribute>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				Copyright PMK Lab
			</td>
		</tr>
	</table>

</body>
</html>

Create new folder named home. Create new jsp file named index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<h3>Home Page</h3>

Create new folder named aboutus. Create new jsp file named index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<h3>About Us Page</h3>

Create new folder named news. Create new jsp file named index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<h3>News Page</h3>

In src\main\webapp\WEB-INF folder, create new folder named tiles folder, create tiles.xml file as below:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

	<definition name="mytemplate" template="/WEB-INF/views/templates/mytemplate.jsp">
		<put-attribute name="content" value="" />
	</definition>

	<definition name="home.index" extends="mytemplate">
		<put-attribute name="content" value="/WEB-INF/views/home/index.jsp" />
	</definition>

	<definition name="aboutus.index" extends="mytemplate">
		<put-attribute name="content" value="/WEB-INF/views/aboutus/index.jsp" />
	</definition>

	<definition name="news.index" extends="mytemplate">
		<put-attribute name="content" value="/WEB-INF/views/news/index.jsp" />
	</definition>

</tiles-definitions>

Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu

Access index method in home controller with following url: http://localhost:9596/home

Output

Access index method in aboutus controller with following url: http://localhost:9596/aboutus

Output

Access index method in news controller with following url: http://localhost:9596/news

Output

I recommend you refer to the books below to learn more about the knowledge in this article: