Java Server Pages

Introduction

JSP stands for JavaServer Pages, a technology used to create dynamic, server-side web content using Java.

  • Extension of Servlet technology

  • Files saved with .jsp extension

  • Allows 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

  • Translation – JSP → Servlet

  • Compilation – Servlet compiled to .class

  • Loading & Instantiation

  • Initialization

  • Request Handling (service method)

  • Destruction

  • <%@ … %> – 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.

Used to declare variables or methods.

Syntax: <%! declaration %>

Example:

<%! int counter = 0; %>
<%! public int getCount() { return counter++; } %>

Used to display output directly to the browser.

Syntax: <%= expression %>

Example:

<%= “Today is: ” + new java.util.Date() %>

Used to write Java code inside JSP.

Syntax:

<% code %>

Example:

<%
String name = “Suresh”;
out.println(“Hello ” + name);
%>

Used to write JSP comments (not sent to the browser).

Syntax: <%-- comment --%>

Example:

<%– This is a JSP comment –%>

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>

<%@ 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>

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>

<%@ 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>