Custom Tags in Spring MVC Framework

This project will demonstrate how to create Custom Tags in Spring MVC Framework

  • SpringMVCFramework
    • src/main/java
      • com.demo
        • SpringMVCFramework.java
      • com.demo.controllers
        • DemoController.java
      • com.demo.entities
        • Product.java
      • com.demo.tags
        • Tag1.java
        • Tag2.java
        • Tag3.java
        • Tag4.java
    • src/main/resources
      • static
      • templates
      • application.properties
    • src
      • main
        • webapp
          • WEB-INF
            • tlds
              • myTags.tld
            • views
              • demo
                • index.jsp
              • tags
                • tag1.jsp
                • tag2.jsp
                • tag3.jsp
                • tag4.jsp
    • pom.xml
package com.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringMVCFramework {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringMVCFramework.class, args);
        }
    }
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(value = { "", "demo" })
public class DemoController {

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

}
package com.demo.entities;

public class Product {

    private String id;
    private String name;
    private double price;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Product(String id, String name, double price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Product() {
        super();
    }

}
package com.demo.tags;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.springframework.web.servlet.tags.RequestContextAwareTag;

public class Tag1 extends RequestContextAwareTag {

    private static final long serialVersionUID = 1L;

    @Override
    public void doFinally() {
        JspWriter out = pageContext.getOut();
        try {
            String jspPage = "../tags/tag1.jsp";
            HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
            request.getRequestDispatcher(jspPage);
            pageContext.include(jspPage);
        } catch (Exception e) {
            try {
                out.print(e.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

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

}
package com.demo.tags;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.springframework.web.servlet.tags.RequestContextAwareTag;

public class Tag2 extends RequestContextAwareTag {

    private static final long serialVersionUID = 1L;

    @Override
    public void doFinally() {
        JspWriter out = pageContext.getOut();
        try {
            String jspPage = "../tags/tag2.jsp";
            HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
            request.setAttribute("age", 20);
            request.setAttribute("username", "abc");
            request.getRequestDispatcher(jspPage);
            pageContext.include(jspPage);
        } catch (Exception e) {
            try {
                out.print(e.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

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

}
package com.demo.tags;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.springframework.web.servlet.tags.RequestContextAwareTag;

import com.demo.entities.Product;

public class Tag3 extends RequestContextAwareTag {

    private static final long serialVersionUID = 1L;

    @Override
    public void doFinally() {
        JspWriter out = pageContext.getOut();
        try {
            String jspPage = "../tags/tag3.jsp";
            HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
            request.setAttribute("product", new Product("p01", "name 1", 4.5));
            request.getRequestDispatcher(jspPage);
            pageContext.include(jspPage);
        } catch (Exception e) {
            try {
                out.print(e.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

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

}
package com.demo.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.springframework.web.servlet.tags.RequestContextAwareTag;

import com.demo.entities.Product;

public class Tag4 extends RequestContextAwareTag {

    private static final long serialVersionUID = 1L;

    @Override
    public void doFinally() {
        JspWriter out = pageContext.getOut();
        try {
            String jspPage = "../tags/tag4.jsp";
            HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
            List<Product> products = new ArrayList<Product>();
            products.add(new Product("p01", "name 1", 4.5));
            products.add(new Product("p02", "name 2", 2));
            products.add(new Product("p03", "name 3", 3));
            request.setAttribute("products", products);
            request.getRequestDispatcher(jspPage);
            pageContext.include(jspPage);
        } catch (Exception e) {
            try {
                out.print(e.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

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

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

server.port=9596
<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>My Tags</short-name>
    <uri>mytags</uri>

    <tag>
        <name>tag1</name>
        <tag-class>com.demo.tags.Tag1</tag-class>
        <body-content>empty</body-content>
    </tag>

    <tag>
        <name>tag2</name>
        <tag-class>com.demo.tags.Tag2</tag-class>
        <body-content>empty</body-content>
    </tag>

    <tag>
        <name>tag3</name>
        <tag-class>com.demo.tags.Tag3</tag-class>
        <body-content>empty</body-content>
    </tag>

    <tag>
        <name>tag4</name>
        <tag-class>com.demo.tags.Tag4</tag-class>
        <body-content>empty</body-content>
    </tag>

</taglib>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="mt" uri="mytags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>

    <mt:tag1 />
    <br>
    <mt:tag2 />
    <br>
    <mt:tag3 />
    <br>
    <mt:tag4 />

</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<h3>Tag 1</h3>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<h3>Tag 2</h3>
age: ${age}
<br>
username: ${username}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<h3>Tag 3</h3>
id: ${product.id}
<br>
name: ${product.name}
<br>
price: ${product.price}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<h3>Tag 4</h3>
<c:forEach var="product" items="${products }">
    id: ${product.id}
    <br>
    name: ${product.name}
    <br>
    price: ${product.price}
    <br>
    =========================
    <br>
</c:forEach>
<?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>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

Screenshots