JavaServer Pages (JSP) is a server-side technology that simplifies the creation of dynamic web content. This article explores JSP concepts, its tag structure, and how to create custom tag libraries.
JSP files are HTML files with embedded Java code. These files have a .jsp
extension and are processed by a servlet container like Apache Tomcat.
Example of a basic JSP file:
<%-- A simple JSP file --%> <html> <body> <h1>Welcome to JSP!</h1> Current Date and Time: <%= new java.util.Date() %> </body> </html>
Save this file as index.jsp
in the root folder of your web application and access it via a browser to see the output.
JSP supports different types of tags for embedding Java code, scripting logic, or accessing JavaBeans. The primary tag types are:
Used to embed Java code in JSP. The syntax is <% code %>
.
Example:
<% int number = 10; out.println("The number is: " + number); %>
Used to display values directly in the output. The syntax is <%= expression %>
.
Example:
<h2>Current Year: <%= java.time.Year.now() %></h2>
Used to declare variables or methods that can be used in JSP. The syntax is <%! code %>
.
Example:
<%! int addNumbers(int a, int b) { return a + b; } %> <h2>Sum: <%= addNumbers(5, 3) %></h2>
JSP directives provide instructions to the JSP container. Common directives include:
<%@ page language="java" contentType="text/html" %>
<%@ include file="header.jsp" %>
<%@ taglib uri="custom-tag-uri" prefix="tag" %>
JavaBeans are reusable components that can be used in JSP to store and retrieve data.
Example:
<!-- JavaBean Class: User.java --> public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
In JSP:
<jsp:useBean id="user" class="User" /> <jsp:setProperty name="user" property="name" value="John Doe" /> <h2>Welcome, <jsp:getProperty name="user" property="name" /></h2>
Custom tags allow you to create reusable components for JSP. These tags are implemented using Java classes and packaged in a JAR file with a TLD (Tag Library Descriptor) file.
Example:
<!-- Custom Tag: HelloTag.java --> import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println("<h1>Hello from Custom Tag!</h1>"); } }
Create a TLD file:
<?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <tlib-version>1.0</tlib-version> <uri>custom-tag-uri</uri> <tag> <name>hello</name> <tag-class>HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
In JSP:
<%@ taglib uri="custom-tag-uri" prefix="ct" %> <ct:hello />
This article covered the basics of JSP, its tags, and directives. It also introduced using JavaBeans and custom tag libraries to build reusable and efficient components for dynamic web applications.