JSP
JSP
JSP simplifies web development by combining the strengths of Java with the
flexibility of HTML. Some advantages of JSP over Servlets are listed below:
JSP Architecture
Page
Maintenance
Easier to maintain More challenging
.
Steps to Create a JSP Application
JSP allows us to embed Java code within HTML pages and making it easy to
create dynamic content. Let us start with a simple exercise to convert an
existing HTML file into a JSP file.
<!DOCTYPE html>
<html>
<body>
Hello! The time is now <%= new java.util.Date() %>
</body>
</html>
Explanation:
The <%= %> tags enclose a Java expression.
new java.util.Date() expression retrieves the current date and time.
When the JSP page is loaded in the browser, the Java expression is
evaluated at runtime, and output is embedded into the HTML.
Each time you reload the page, it displays the current time, demonstrating
how JSP dynamically generates HTML content based on Java logic.
JSP Elements
JSP has several elements which can be divided into 4 different types.
Expression
Scriplets
Directives
Declarations
1. Expression
This tag is used to output any data on the generated page. These data are
automatically converted to a string and printed on the output stream.
Syntax:
<%= “Anything” %>
JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends
with %>. Between these, you can put anything that will convert to the String
and that will be displayed.
Example:
<%=”HelloWorld!” %>
2. Scriplets
This allows inserting any amount of valid Java code. These codes are placed
in the _jspService() method by the JSP engine.
Syntax:
<%
// Java codes
%>
Note: JSP Scriptlets begins with <% and ends %> . We can embed any
amount of Java code in the JSP Scriptlets. JSP Engine places these codes in
the _jspService() method.
Example:
<%
String name = “Java”;
out.println(“Hello, ” + name);
%>
Request
Response
Session
Out
3. Directives
A JSP directive starts with <%@ characters. In the directives, we can import
packages, define error-handling pages, or configure session information for
the JSP page.
Syntax:
4. Declarations
This is used for defining functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
JSP Declaratives begins with <%! and ends %> with We can embed any
amount of java code in the JSP Declaratives. Variables and functions defined
in the declaratives are class-level and can be used anywhere on the JSP
page.
Example:
Example:
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<body>
<% out.println("Hello there!"); %>
</body>
</html>