UNIT -4 INTRODUCTIONS TO JSP
The problem with servlet
Configuration Issues
Incorrect mapping in [Link] or annotation (@WebServlet)
Deployment descriptor missing or malformed
Compilation Errors
Servlet API not found in classpath ([Link].*)
Syntax or import issues
Runtime Errors
HTTP 404: Servlet not found
HTTP 500: Internal server error, possibly due to logic bugs or exceptions
NullPointerException from uninitialized objects
Deployment Issues
Servlet not running on server (e.g., Tomcat/Jetty)
WAR file not properly deployed
Request Handling Problems
doGet() or doPost() not handling request properly
Encoding issues with form data
Session/Context Issues
Session data not persisting
Context attributes behaving unexpectedly
The Anatomy of a JSP Page
The anatomy of a JSP (JavaServer Pages) page consists of several key elements that work
together to build dynamic web content. Here's a breakdown of the components:
1. Directives
These provide global information about the JSP page to the container.
Common Directives:
<%@ page ... %>: Defines page-level settings like content type, language, error
page, etc.
Example: <%@ page language="java" contentType="text/html" pageEncoding="UTF-8" %>
<%@ include file="[Link]" %>: Includes a static file at translation time.
<%@ taglib ... %>: Declares a tag library used in the page.
2. Scriptlets
Java code written between <% and %>. Runs when the page is requested.
<%
String name = "Alice";
[Link]("Hello, " + name);
%>
Scriptlets are discouraged in modern JSP—use JSTL or Expression Language
instead.
3. Expressions
Outputs a value directly into the response. Written as <%= expression %>.
%= new [Link]() %>
4. Declarations
Declare variables or methods that are accessible in the JSP.
<%!
int counter = 0;
public int getCounter() { return counter++; }
%>
5. Actions
Special JSP tags that control behavior, such as including content or forwarding requests.
<jsp:include page="[Link]" />
<jsp:forward page="[Link]" />
6. HTML & Static Content
The regular HTML part of the page is sent to the client as-is. You can mix it with dynamic
parts.
<html>
<body>
<h1>Welcome!</h1>
Current time: <%= new [Link]() %>
</body>
</html>
7. Expression Language (EL) [Modern JSP]
Simplifies access to objects like request, session, application, and JavaBeans.
<p>Hello, ${[Link]}</p>
JSP Processing
When a JSP page is requested by a client, the web server (e.g., Apache Tomcat) processes it
in several stages. Here’s a clear step-by-step breakdown:
1. Request Comes In
A client (like a browser) sends a request for a .jsp page, e.g.,
[Link]
2. JSP Translation
The JSP engine translates the .jsp file into a Java servlet source file.
This servlet contains Java code that corresponds to the HTML and JSP elements in the
page.
Example:
<h1>Hello, <%= name %>!</h1>
becomes in Java:
[Link]("<h1>Hello, ");
[Link](name);
[Link]("!</h1>");
3. Compilation
The generated servlet source file is then compiled into a .class file (Java bytecode).
4. Loading and Instantiation
The compiled servlet class is loaded into memory by the JVM (Java Virtual
Machine).
The container instantiates the servlet.
5. Initialization (jspInit())
The JSP is initialized by calling its jspInit() method (similar to init() in Servlets).
This is done once, when the servlet is loaded for the first time.
6. Request Handling (_jspService())
For each request, the container calls the service() method, specifically
_jspService(HttpServletRequest req, HttpServletResponse res).
This method contains the logic to generate dynamic content (from your original JSP
code).
7. Destruction (jspDestroy())
When the server is shutting down or the JSP is unloaded, jspDestroy() is called to
clean up resources.
8. Subsequent Requests
The servlet (converted from JSP) is already compiled and loaded.
Only the _jspService() method is called again for each new request.
Translation and compilation are skipped unless the JSP changes.
JSP Application Design with MVC Setting UP and JSP Environment
MVC = Model - View - Controller
Layer Role Technologies
Model Business logic, data access JavaBeans, JDBC, DAO, Hibernate
View UI presentation JSP, HTML, CSS, JSTL, EL
Controller Request handling Servlet
Flow of Control in MVC (JSP)
1. Client sends a request → to a Controller (Servlet)
2. Controller processes the request, interacts with the Model
3. Model fetches/stores data from the database
4. Controller sets data into request/session scope
5. Forwards to a View (JSP) for rendering
6. JSP displays the data (UI)
JSP Environment Setup (Using Apache Tomcat)
Step 1: Install Required Software
Java JDK (e.g., JDK 11+)
Apache Tomcat (e.g., Tomcat 9 or 10)
IDE: Eclipse, IntelliJ IDEA, or VS Code (optional but helpful)
Maven/Gradle (optional for dependency management)
Step 2: Project Structure (Typical)
YourProject/
├── WebContent/ (or src/main/webapp/)
│ ├── [Link]
│ ├── views/
│ │ └── [Link]
│ └── WEB-INF/
│ └── [Link]
├── src/
│ ├── controller/
│ │ └── [Link]
│ ├── model/
│ │ └── [Link]
Step 3: [Link] Configuration
<web-app>
<servlet>
<servlet-name>HelloController</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloController</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Example: Simple MVC with JSP
1 Model (JavaBean) – [Link]
package model;
public class User {
private String name;
public User(String name) { [Link] = name; }
public String getName() { return name; }
}
2 Controller (Servlet) – [Link]
package controller;
import [Link];
import [Link].*;
import [Link].*;
import [Link];
public class HelloController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = [Link]("name");
User user = new User(username);
[Link]("user", user);
RequestDispatcher rd = [Link]("views/[Link]");
[Link](request, response);
}
}
3 View (JSP) – [Link]
<%@ page import="[Link]" %>
<%
User user = (User) [Link]("user");
%>
<html>
<body>
<h2>Hello, <%= [Link]() %>!</h2>
</body>
</html>
Running the App
1. Deploy the project on Apache Tomcat
2. Access: [Link]
3. Output: Hello, John! (from the [Link] view)
Installation the java software Development kit
JDK (Java Development Kit): Required to compile and run Java programs.
Latest version: JDK 17 or 21 (LTS versions recommended)
Step-by-Step: Install JDK
Step 1: Download the JDK
Go to the official Oracle or OpenJDK website:
Oracle JDK: [Link]
OpenJDK (free & open-source): [Link]
Choose the version that fits your OS:
Windows
macOS
Linux
Step 2: Install JDK (by OS)
On Windows
1. Run the .exe installer
2. Follow the installation wizard
3. By default, JDK installs in:
C:\Program Files\Java\jdk-17
4. Set the Environment Variable:
o Search for Environment Variables in Start Menu
o Under System Variables, add:
JAVA_HOME = C:\Program Files\Java\jdk-17
Add ;%JAVA_HOME%\bin to the Path variable
Tomcat server & testing Tomcat
What is Apache Tomcat?
Apache Tomcat is a web server and servlet container used to run Java web applications like
JSPs and Servlets.
Step-by-Step: Install and Test Apache Tomcat
Step 1: Download Apache Tomcat
Go to the official site:
[Link]
Click on the “Download” link for the latest stable version (e.g., Tomcat 10 or 9)
Download the Core zip (Windows) or [Link] (Linux/macOS)
Step 2: Extract and Set Up Tomcat
Extract the downloaded archive to a location of your choice. Example:
C:\apache-tomcat-10.1.20\
/home/username/apache-tomcat-10.1.20/
Folder structure:
pgsql
CopyEdit
bin/ – Start/stop scripts
conf/ – Configuration files ([Link], [Link])
logs/ – Log files
webapps/ – Place your .war or app folders here
Step 3: Set JAVA_HOME (Important)
Tomcat needs to know where Java is installed.
Windows:
set JAVA_HOME=C:\Program Files\Java\jdk-17
Linux/macOS:
Add this to your ~/.bashrc or ~/.zshrc:
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
Step 4: Start Tomcat Server
Navigate to the bin/ directory and run:
On Windows:
Double-click [Link]
(or run it from CMD):
cd apache-tomcat-10.x.x/bin
[Link]
On Linux/macOS:
cd apache-tomcat-10.x.x/bin
./[Link]
Step 5: Test Tomcat in Browser
Open your browser and go to:
[Link]
You should see the Tomcat Welcome Page ✅
If it doesn’t work:
Check if port 8080 is busy (you can change it in conf/[Link])
Check if JAVA_HOME is correctly set
Try running as administrator/sudo
Step 6: Test a Simple JSP
1. Create a JSP file: Save this as [Link] in the webapps/ROOT/ directory:
<html>
<body>
<h2>Hello from Tomcat JSP!</h2>
Current time: <%= new [Link]() %>
</body>
</html>
2. Restart Tomcat (or refresh the page)
3. Visit:
[Link]
You should see your JSP file in action!