Java Server Pages
Introduction
JSP stands for JavaServer Pages, a technology used to create dynamic, server-side web content using Java.
Features & Advntages
Extension of Servlet technology
Files saved with
.jspextensionAllows mixing of HTML and Java code
Compiled into Servlets by the server (e.g., Apache Tomcat)
Easier to write than servlets (less Java code)
Separation of presentation (HTML) and logic (Java)
Reusable components using JavaBeans and custom tags
Compiling Process
Translation – JSP → Servlet
Compilation – Servlet compiled to
.classLoading & Instantiation
Initialization
Request Handling (service method)
Destruction
Common JSP tags
<%@ … %> – Directive
<%! … %> – Declaration
<%= … %> – Expression
<% … %> – Scriptlet
Directive tag
Used to give global information about the page.
Syntax:
<%@ directive attribute="value" %>
Example:
<%@ page language=”java” contentType=”text/html” %>
Common Directives:
page: Defines page-dependent attributes.include: Includes another file during the translation phase.taglib: Declares custom tag libraries.
Declaration tag
Used to declare variables or methods.
Syntax: <%! declaration %>
Example:
<%! int counter = 0; %>
<%! public int getCount() { return counter++; } %>
Expression tag
Used to display output directly to the browser.
Syntax: <%= expression %>
Example:
<%= “Today is: ” + new java.util.Date() %>
Scriptlet tag
Used to write Java code inside JSP.
Syntax:
<% code %>
Example:
<%
String name = “Suresh”;
out.println(“Hello ” + name);
%>
Comment tag
Used to write JSP comments (not sent to the browser).
Syntax: <%-- comment --%>
Example:
<%– This is a JSP comment –%>
Example - 1
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<title>Insert title here</title>
</head>
<body>
<form action=“hello.jsp”>
<input type=“submit” value=“Click Me” />
</form>
</body>
</html>
Hello.jsp
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<title>Insert title here</title>
</head>
<body>
<%
out.println(“Hello, welcome to JSP”);
%>
</body>
</html>
Example - 2
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<title>Insert title here</title>
</head>
<body>
<form action=“wish.jsp”>
<label>Enter Your Name :</label>
<input type=“text” name=“txtname” size=“30”/>
<input type=“submit” value=“Say wish” />
</form>
</body>
</html>
wish.jsp
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<title>Insert title here</title>
</head>
<body>
<%
String na = request.getParameter(“txtname”);
out.println(“Hello, “+na+“, Welcome to JSP “);
%>
</body>
</html>
