Show List

Basic JSP syntax

Here's an explanation of the basic JSP (JavaServer Pages) syntax, with some code examples:

JSP uses tags to separate Java code from HTML markup. The most commonly used JSP tags are:

  1. <%@ ... %>: JSP directives that specify various configuration and page-specific information.
  2. <%= ... %>: JSP expressions that evaluate a Java expression and output the result to the HTML response.
  3. <% ... %>: JSP scriptlets that contain Java code that is executed when the JSP page is translated into a servlet.

Here's an example JSP page that uses each of these tags:

jsp
Copy code
<%@ page language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>My JSP Page</title> </head> <body> <h1>Today the date is <%= new java.util.Date() %></h1> <% int count = 5; for (int i = 0; i < count; i++) { %> <p>This is paragraph <%= i+1 %> of <%= count %></p> <% } %> <c:if test="${1+1 == 2}"> <p>This will always be true</p> </c:if> </body> </html>

In this example, we're using the JSP directive <%@ page %> to specify the language for the JSP page (in this case, Java), and <%@ taglib %> to import the JSTL (JavaServer Pages Standard Tag Library) core library.

We're also using the JSP expression <%= ... %> to output the current date, and the JSP scriptlet <% ... %> to loop through a block of code and output a paragraph for each iteration.

Finally, we're using the JSTL tag <c:if> to conditionally output a paragraph based on the result of an expression.


    Leave a Comment


  • captcha text