Search code examples
javajsptldcustom-tags

How to include a JSP page into a custom tag


I am creating a custom tag directive where I have to print a table of data from database.

So far I have created:

JSP page:

 <%@taglib uri="/WEB-INF/tlds/fact.tld" prefix="veritis"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>       
        <h1><veritis:print name="emp" /></h1> 
    </body>
</html>

TLD file:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
 <tlib-version>1.0</tlib-version>
 <short-name>factorial</short-name>
  <tag>
      <name>print</name>
      <tag-class>com.veritis.jsp.FactTag</tag-class>
      <body-content>empty</body-content>
    <attribute>
        <name>name</name>
        <required>false</required>
    </attribute>
  </tag>
</taglib>

and a Class file for which fetches data from database using other Class file. This class file also extends TagSupport to overwrite needed TLD methods.

public class FactTag extends TagSupport{
    String value="emp";
    public String getValue() {
        return value;    }

    public void setValue(String value) {
        this.value = value;
    }
    public int doStartTag(){
        return Tag.SKIP_BODY;
    }
    public int doEndTag() throws JspTagException{

        String emp1=getValue();
            
       try{
           //The following line is to get the JSP Writer Object
           //similar to PrintWriter in Servlet
           JspWriter out=pageContext.getOut();
           
           TableData tbd=new TableData();
           List<Employee> listOfEmp=tbd.getAllEMployees();
           for(Employee emp:listOfEmp)
           {
               System.out.println(emp);
           }
       }catch(Exception e){}
       return Tag.SKIP_PAGE;
    }
   
}

Now I have data in my List<emp> and I want to print that in JSP file. I could print that by using out object but my requirement is not to use out object rather print by including other JSP file or any other way.

Note: Though I am taking input(emp) from JSP, I am not using it for now. Rather I am generating a static query to fetch the data.


Solution

  • You can use JSTL c:forEach tag to iterate through the list of Employee. If you don't want to use frameworks based on servlets like Struts2 or Spring MVC, you can use raw servlet

    @WebServlet("/employees")
    public class HomeServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            TableData tbd=new TableData();
            List<Employee> listOfEmp=tbd.getAllEMployees();        
            request.setAttribute("listOfEmp", listOfEmp);
    
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/emloyee.jsp");
            rd.forward(request, response);
        }
    
    }
    

    employee.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>JSP Page</title>
    <style>
    table,th,td
    {
    border:1px solid black;
    }
    </style>
    </head>
    <body>
    <%-- Using JSTL c:forEach and c:out to loop a list and display items in a table --%>
    <table>
    <tbody>
    <tr><th>ID</th><th>Name</th><th>Role</th></tr>
    <c:forEach items="${requestScope.listOfEmp}" var="emp">
    <tr><td><c:out value="${emp.id}"></c:out></td>
    <td><c:out value="${emp.name}"></c:out></td>
    <td><c:out value="${emp.role}"></c:out></td></tr>
    </c:forEach>
    </tbody>
    </table>
    <br><br>
    </body>
    </html>
    

    You can also use JSP fragment page containing a table and include it to the main page.

    employee.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>JSP Page</title>
    <style>
    table,th,td
    {
    border:1px solid black;
    }
    </style>
    </head>
    <body>
    <c:import url="employee_table.jsp"/>
    <br><br>
    </body>
    </html>
    

    employee_table.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%-- Using JSTL c:forEach and c:out to loop a list and display items in a table --%>
    <table>
    <tbody>
    <tr><th>ID</th><th>Name</th><th>Role</th></tr>
    <c:forEach items="${requestScope.listOfEmp}" var="emp">
    <tr><td><c:out value="${emp.id}"></c:out></td>
    <td><c:out value="${emp.name}"></c:out></td>
    <td><c:out value="${emp.role}"></c:out></td></tr>
    </c:forEach>
    </tbody>
    </table>