ASP (ACTIVE SERVER PAGES)
Introduction to ASP
ASP (Active Server Pages) is a server-side scripting technology developed by Microsoft for creating
dynamic and interactive web applications. ASP pages are executed on the server, and the final HTML
output is sent to the client’s browser. It was widely used before the introduction of [Link] and
remains important for understanding server-side programming concepts.
ASP files have the extension ".asp" and contain a mixture of HTML and server-side scripts written in
VBScript or JavaScript.
Features of ASP
1. Server-Side Execution: ASP code runs on the server, not on the client machine.
2. Built-In Objects: ASP provides several predefined objects such as Request, Response, Session,
Application, and Server.
3. Scripting Language Support: ASP supports VBScript, JScript, and JavaScript.
4. Dynamic Content: ASP can generate dynamic web pages based on user input, database
results, and session data.
5. Database Connectivity: ASP uses ADO (ActiveX Data Objects) to interact with databases such
as SQL Server, Oracle, and MS Access.
6. Integration: ASP allows embedding scripting code directly inside HTML pages.
7. Platform Dependent: Works best on Windows servers running IIS (Internet Information
Services).
How ASP Works (Execution Process)
1. The browser sends a request for an ASP page.
2. The IIS web server receives the request.
3. The ASP engine processes the script inside the page.
4. Server executes the code, communicates with the database if needed, and prepares the
output.
5. Final HTML is sent back to the client’s browser.
6. The browser displays the page; server-side script remains invisible to the user.
Syntax and Structure in ASP
ASP code is written inside script delimiters:
<%
' VBScript code goes here
[Link]("Hello from ASP")
%>
HTML and ASP code can exist together in one file.
ASP Built-In Objects
1. Request Object
Used to collect data sent by the user through forms, query strings, or cookies.
Example:
name = [Link]("username")
2. Response Object
Used to send output back to the client.
Example:
[Link]("Welcome to ASP!")
3. Session Object
Stores user-specific data across multiple pages.
Example:
Session("username") = "Namita"
4. Application Object
Stores data shared across all users of the application.
Example:
Application("count") = 100
5. Server Object
Provides methods to encode text, create components, and manage errors.
Example:
[Link]("<Hello>")
Variables and Control Structures in ASP
Declaring a variable:
<%
Dim x
x = 10
%>
If condition:
<%
If x > 5 Then
[Link]("x is greater than 5")
End If
%>
Loop example:
<%
For i = 1 To 5
[Link](i & "<br>")
Next
%>
Database Connectivity in ASP (Using ADO)
Example program:
<%
Set conn = [Link]("[Link]")
[Link] "DSN=studentDB"
Set rs = [Link]("SELECT * FROM students")
Do While Not [Link]
[Link](rs("name") & "<br>")
[Link]
Loop
[Link]
[Link]
%>
ADO allows ASP to connect to databases, execute SQL commands, and process records.
Error Handling in ASP
ASP supports basic error handling using:
On Error Resume Next
To check for errors:
<%
If [Link] <> 0 Then
[Link]("An error has occurred!")
End If
%>
Advantages of ASP
1. Easy to learn and integrate with HTML.
2. Supports session tracking and state management.
3. Provides built-in objects for handling web operations.
4. Enables rapid development of dynamic web pages.
5. Supports database-driven applications.
Disadvantages of ASP
1. Platform dependent (Windows/IIS only).
2. Uses interpreted scripting, slower than [Link].
3. Not suitable for very large applications.
4. Limited debugging and error handling.
5. Outdated technology compared to modern frameworks.
Real-World Uses of ASP
ASP was commonly used for:
Login and authentication systems
Online forms and surveys
Guestbook applications
Shopping cart systems
Dynamic content management
Simple ASP Program Example
[Link]:
<html> <body> <% username = [Link]("name") [Link]("Hello " & username)
%> </body> </html>
If you visit:
[Link]
Output will be:
Hello Namita
INTRODUCTION TO [Link]
Introduction
[Link] is a powerful server-side web development framework created by Microsoft. It is the
successor to ASP (Active Server Pages) and is built on top of the .NET Framework. [Link] enables
developers to build dynamic, scalable, and high-performance web applications using modern
programming languages such as C# and [Link].
[Link] is compiled rather than interpreted, which makes it faster, more secure, and more efficient
than classic ASP. It also provides an event-driven programming model similar to Windows
applications.
Key Features of [Link]
1. Compiled Code
Unlike classic ASP which uses interpreted scripts, [Link] code is compiled into .NET
assemblies. This results in faster execution and better performance.
2. Multiple Language Support
[Link] supports C#, [Link], and more than 40 other .NET languages. Developers can
choose the language they are comfortable with.
3. Rich Server Controls
[Link] provides a large set of built-in server controls such as GridView, TextBox, Button,
Calendar, and DropDownList that simplify UI development.
4. State Management
[Link] supports multiple ways to maintain data between requests:
o ViewState
o Session
o Cache
o Cookies
o Application state
5. Built-in Security Features
[Link] provides authentication, authorization, and role-based security to protect web
applications.
6. Powerful Database Connectivity
[Link] uses [Link] to work with databases such as SQL Server, MySQL, and Oracle.
[Link] provides efficient data access and disconnected architecture.
7. XML and Web Services Support
[Link] supports XML, SOAP, REST, and Web API, making it useful for service-oriented
applications.
8. Automatic Memory Management
[Link] benefits from the .NET garbage collector, which automatically handles memory
allocation and deallocation.
9. Error Handling
[Link] provides modern error handling using try-catch blocks and custom error pages.
[Link] Architecture
[Link] uses a layered architecture:
1. Presentation Layer – WebForms, Razor Pages, or MVC Views
2. Business Layer – C# classes handling logic
3. Data Layer – [Link] or Entity Framework for database operations
[Link] supports three development models:
1. Web Forms
o Event-driven
o Drag-and-drop controls
o Uses ViewState to maintain page information
2. [Link] MVC
o Model–View–Controller pattern
o Clean separation of concerns
o Better for large, scalable applications
3. [Link] Web API
o For building RESTful services
o Used for mobile and cloud applications
How [Link] Works
1. A user sends a request from the browser.
2. IIS (Internet Information Services) receives the request.
3. The request is passed to the [Link] engine.
4. The requested page (.aspx) is compiled into a .NET class (if not already compiled).
5. The server executes the class and generates HTML output.
6. The HTML response is sent back to the user's browser.
This compiled model ensures high speed and reliability.
[Link] Page Structure
A basic [Link] Web Form file:
<%@ Page Language="C#" %>
<html>
<body>
<form runat="server">
<asp:Label ID="Label1" runat="server" Text="Hello [Link]"></asp:Label>
</form>
</body>
</html>
Key points:
The <%@ Page %> directive defines page settings.
<asp:...> tags are server controls.
runat="server" ensures the control is processed on the server.
Advantages of [Link]
1. Faster performance due to compiled code.
2. Strongly typed languages reduce errors.
3. Built-in caching improves speed.
4. Large tool support in Visual Studio.
5. Enhanced security with built-in authentication.
6. Automatic memory management.
7. Easy integration with databases.
8. Separation of logic and presentation (MVC).
Disadvantages of [Link]
1. Runs best on Windows servers (IIS required).
2. More complex than classic ASP for beginners.
3. Limited control without Visual Studio.
4. ViewState in WebForms can increase page size.
Real-World Applications of [Link]
[Link] is used in:
E-commerce websites
Online banking systems
ERP systems
Inventory management
Social networking sites
Web portals
Cloud-based applications
Companies using [Link] include Microsoft, Dell, GoDaddy, StackOverflow, and many enterprise
businesses.
JAVA SERVER PAGES (JSP) – DESCRIPTIVE NOTES
Introduction
Java Server Pages (JSP) is a server-side technology developed by Sun Microsystems (now Oracle) for
creating dynamic, platform-independent web applications. JSP allows embedding Java code directly
into HTML pages, enabling the development of interactive and database-driven websites. JSP is built
on top of Java Servlets and provides a simpler, more convenient way to generate dynamic web
content.
JSP pages are saved with the extension ".jsp".
Features of JSP
1. Platform Independent
JSP is written in Java, making it portable across all operating systems and servers that
support Java.
2. Separation of Logic and Presentation
JSP allows mixing HTML with server-side Java code, making web page design easier.
3. Built on Servlets
JSP is translated into a Servlet by the web container and then executed, combining power
with simplicity.
4. Automatic Compilation
JSP pages are automatically compiled into Java classes when first requested.
5. Reusable Components
JSP supports the use of JavaBeans, custom tags, and JSP tag libraries.
6. Rich Implicit Objects
JSP provides several predefined objects like request, response, session, and application.
7. Integration with Databases
JSP uses JDBC (Java Database Connectivity) to connect to and interact with databases.
8. High Performance
Since JSP is converted into a Servlet, it executes faster after initial compilation.
JSP Life Cycle
A JSP page goes through the following stages:
1. Translation
The JSP file is translated into a Servlet source file.
2. Compilation
The generated Servlet source is compiled into bytecode (.class file).
3. Loading
The class is loaded by the class loader.
4. Instantiation
A new instance of the Servlet is created.
5. Initialization (jspInit)
Called once when the JSP is first loaded.
6. Execution (service method)
Executes the request and sends response to client.
7. Destruction (jspDestroy)
Called when the server shuts down or JSP is recompiled.
JSP Syntax and Scripting Elements
JSP provides three main scripting elements:
1. Scriptlet (for Java code):
<%
int x = 10;
%>
2. Expression (outputs directly to page):
<%= x * 2 %>
3. Declaration (declares variables/methods at class level):
<%!
int count = 0;
public int add(int a, int b) { return a + b; }
%>
JSP Directives
Directives provide instructions to the JSP engine.
1. Page Directive
Controls page-level settings.
Example:
<%@ page language="java" import="[Link].*" %>
2. Include Directive
Includes a file statically.
Example:
<%@ include file="[Link]" %>
3. Taglib Directive
Used to import custom tag libraries.
Example:
<%@ taglib uri="myTags" prefix="mt" %>
JSP Implicit Objects
JSP provides nine implicit objects that can be used directly without declaration:
1. request – represents client's request
2. response – used to send output to client
3. out – writes content to browser
4. session – stores user-specific data
5. application – shared data for entire application
6. config – servlet configuration
7. pageContext – provides access to all scopes
8. page – reference to current JSP page
9. exception – handles runtime errors
Example:
Hello <%= [Link]("user") %>
JSP with Database (Using JDBC)
Example JSP code:
<%@ page import="[Link].*" %>
<%
Connection con = [Link]("jdbc:mysql://localhost/test","root","");
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
while([Link]()) {
[Link]([Link]("name") + "<br>");
}
[Link]();
%>
Benefits of JSP
1. Easy to write dynamic web pages.
2. Java-based → portable and secure.
3. Automatically compiled into Servlets.
4. Supports tag libraries and JavaBeans.
5. Improved performance after first execution.
6. Clean separation of business logic and layout.
Limitations of JSP
1. Embedding too much Java code inside HTML reduces readability.
2. Debugging JSP pages is more difficult than debugging Servlets.
3. Requires knowledge of Java programming.
4. Initial compilation takes extra time.
JSP vs Servlets
Aspect JSP Servlet
Purpose Presentation (View) Logic/Control
Syntax HTML + Java Pure Java
Speed Faster after first call Faster for repeated logic
Best Use Web pages Processing requests
Real-Life Uses of JSP
Online forms and user authentication
E-commerce product pages
Airline/train ticket booking systems
Web portals and dashboards
Online banking and billing systems
News and content management systems
Example: Simple JSP Page
[Link]
<html> <body> <% String name = [Link]("name"); [Link]("Hello " + name); %>
</body> </html>
URL:
[Link]
Output:
Hello Namita
JSP APPLICATION DESIGN – DESCRIPTIVE NOTES
Introduction
JSP (Java Server Pages) application design refers to the method of organizing the components of a
web application so that the application is easy to develop, understand, maintain, and extend. A well-
designed JSP application separates presentation, business logic, database handling, and navigation.
JSP is mainly used for creating dynamic web pages and works together with Servlets, JavaBeans, and
JDBC.
1. Goals of JSP Application Design
1. To clearly separate presentation (HTML/JSP) from business logic (Java classes).
2. To build scalable and maintainable web applications.
3. To make page navigation and data flow easier to manage.
4. To improve code reusability through JavaBeans and custom tags.
5. To support modular structure following MVC architecture.
2. Basic Architecture of JSP Applications (MVC Architecture)
JSP applications commonly use the Model–View–Controller (MVC) design pattern:
1. Model
o Contains business logic and data access code.
o Includes JavaBeans, POJOs, DAO classes, and JDBC code.
o Responsible for retrieving, updating, and storing data.
2. View (JSP Pages)
o Displays the output to users.
o Contains HTML, CSS, JavaScript, and JSP tags.
o Should have minimum Java code.
3. Controller (Servlets)
o Accepts client requests.
o Calls appropriate models (Java classes).
o Forwards data to JSP for display.
o Controls navigation between pages.
Flow:
Client Request → Servlet (Controller) → Model (Business Logic) → Servlet → JSP (View) → Browser
Output
3. Components Used in JSP Application Design
1. JSP Pages
o Responsible for showing output.
o Can use Expression Language (EL) and JSTL tags.
o Should avoid heavy Java logic.
2. Servlets
o Receive input from user through request object.
o Perform validation and call model classes.
o Forward data to JSP using RequestDispatcher.
3. JavaBeans / POJOs
o Encapsulate data using getters and setters.
o Used to transfer data between JSP and Servlets.
4. DAO (Data Access Objects)
o Handle all database operations using JDBC.
o Improve modularity and reusability.
5. JDBC Connectivity
o Used for interacting with relational databases (MySQL, Oracle, etc.).
6. JSP Implicit Objects
o request, response, session, application, out, config, exception, page, pageContext
o Help manage user sessions, inputs, outputs, and application-level data.
4. Typical Folder Structure of JSP Application
MyWebApp/
├── [Link]
├── [Link]
├── [Link]
├── WEB-INF/
│ ├── [Link]
│ ├── classes/ (Java compiled classes)
│ └── lib/ (JAR files)
├── css/
├── js/
└── images/
5. Steps in JSP Application Design
1. Create JSP Pages for user interface (login form, registration page, dashboards).
2. Create Servlets for handling requests and controlling page navigation.
3. Design JavaBeans to store and pass user data.
4. Implement Database Layer using JDBC and DAO classes.
5. Configure [Link] for servlet mappings or use annotations (@WebServlet).
6. Deploy the application on a web server such as Apache Tomcat.
7. Test and debug using logs and JSP error pages.
6. Example of JSP Application Flow (Login System)
1. User enters login details in [Link].
2. Form submits data to LoginServlet (/login).
3. Servlet validates data and calls UserDAO for verification.
4. If successful → redirect to [Link].
5. If failure → return to [Link] with error message.
7. Advantages of Good JSP Application Design
1. Easy to maintain and update.
2. Better performance because logic is separated.
3. Clear organization of files and components.
4. Supports reusable components (JavaBeans, custom tags).
5. Makes debugging and testing easier.
6. Allows multiple developers to work simultaneously (UI vs Backend).
8. Best Practices for JSP Application Design
1. Use JSP mainly as a View, not to write business logic.
2. Use Servlets for controlling application flow.
3. Use JavaBeans or POJOs to store and manage application data.
4. Use DAO classes for database operations.
5. Use JSTL and EL instead of scriptlets (<% %>).
6. Use filters for authentication, logging, and encoding.
7. Store sensitive information in session objects, not in hidden fields or URLs.
8. Use server-side validation for security.
TOMCAT SERVER – DESCRIPTIVE NOTES
Introduction
Apache Tomcat is an open-source web server and servlet container developed by the Apache
Software Foundation. It is the official reference implementation for Java Servlet, JavaServer Pages
(JSP), Java Expression Language (EL), and WebSocket technologies. Tomcat is widely used for
developing and deploying Java-based web applications.
Tomcat is lightweight, easy to configure, and widely used in academic and enterprise environments
for running JSP pages and Servlets.
1. What is Tomcat Server?
Tomcat is not just a web server — it is also a Servlet Container. This means it can:
1. Execute Java Servlets
2. Process JSP pages
3. Convert JSP into Servlets
4. Manage servlet lifecycle (init, service, destroy)
5. Handle sessions, security, and resource pooling
Tomcat uses HTTP protocol for transferring data between client and server and supports dynamic
content generation with Java programs.
2. Features of Apache Tomcat
1. Open Source – Free to use and backed by a strong community.
2. Lightweight – Lower memory footprint compared to enterprise servers like WebLogic or
JBoss.
3. Servlet and JSP Support – Fully implements Java Servlet and JSP specifications.
4. Cross-Platform – Works on Windows, Linux, macOS.
5. Easy Deployment – WAR file deployment is simple and fast.
6. Built-in Web Server – Eliminates the need for a separate HTTP server for development.
7. Logging Support – Provides server logs for debugging.
8. Security Features – Supports authentication, SSL, secure session management.
9. Administration Tools – A browser-based admin console for managing users and applications.
3. Architecture of Tomcat Server
Tomcat is made up of several components:
1. Catalina (Servlet Container) – Main engine responsible for servlet processing.
2. Coyote (HTTP Connector) – Handles HTTP requests and responses.
3. Jasper (JSP Engine) – Converts JSP files into Servlets.
4. JMX (Java Management Extensions) – For monitoring and management.
5. Realm – Handles authentication and authorization.
6. Cluster – Supports load balancing and session replication.
Tomcat Processing Flow:
Client Request → Coyote HTTP Connector → Catalina Engine → Servlet/JSP → Response Returned to
Client
4. Directory Structure of Tomcat
When you install Tomcat, the following folder structure appears:
apache-tomcat/
├── bin/ (Startup and shutdown scripts)
├── conf/ (Configuration files: [Link], [Link])
├── lib/ (JAR libraries)
├── logs/ (Server logs)
├── temp/ (Temporary files)
├── webapps/ (Deploy web applications)
│ ├── ROOT/
│ ├── examples/
│ ├── manager/
│ └── YourApp/
└── work/ (JSP to Servlet translation files)
Important files:
[Link] – Main configuration file for ports, connectors, hosts.
[Link] (global) – Default web application settings.
[Link] – Log file for debugging.
5. Installing Tomcat Server
Steps:
1. Download Tomcat from: [Link]
2. Extract the ZIP/installer.
3. Set environment variable JAVA_HOME.
4. Start Tomcat using scripts:
o Windows: /bin/[Link]
o Linux/Mac: /bin/[Link]
5. Open browser and type:
6. [Link]
If Tomcat homepage appears, installation is successful.
6. How Tomcat Works (Execution Process)
1. The user sends a request from browser (e.g., /[Link]).
2. Tomcat receives request via Coyote HTTP connector.
3. Catalina engine identifies the web application.
4. JSP pages are compiled into Servlets by Jasper engine (only once).
5. Servlet’s service() method executes.
6. Response (HTML/CSS/JS) is returned to the browser.
7. Deploying Applications on Tomcat
There are three common methods:
1. Automatic Deployment
o Copy [Link] file into the webapps/ folder.
o Tomcat auto-extracts it.
2. Exploded Directory Deployment
o Copy complete project folder (with WEB-INF) into webapps/.
3. Using Tomcat Manager Web Interface
o Login to [Link]
o Deploy WAR files through browser interface.
8. WEB-INF Folder in Tomcat
Every Java web application must contain:
WEB-INF/
├── [Link] (Deployment descriptor)
├── classes/ (Compiled .class files)
├── lib/ (JAR files like JDBC drivers)
Tomcat does NOT allow direct access to WEB-INF from a browser, making it secure.
9. Logging and Debugging in Tomcat
Logs are located in the logs/ folder.
Important logs:
[Link] – main server log
localhost_access_log – request logs
[Link] – deployment logs
Logs help debug servlet errors, JSP errors, and startup failures.
10. Advantages of Tomcat
1. Lightweight and fast
2. Easy to install and configure
3. Supports Servlets, JSP, WebSockets
4. Excellent documentation
5. Ideal for students, developers, and testing environments
6. Supports SSL for secure communication
11. Disadvantages of Tomcat
1. Not suitable for very large enterprise applications (use JBoss/WebLogic instead)
2. No built-in support for EJB (Enterprise Java Beans)
3. Requires manual tuning for high traffic
12. Real-World Applications of Tomcat
Tomcat is widely used in:
Student and academic projects
Small to medium-scale web applications
REST webpages and APIs
Online shopping systems
Java training institutes
Prototype and testing servers
Companies often use Tomcat for microservices and internal tools.
SP OBJECTS – DESCRIPTIVE NOTES
Introduction
JSP (Java Server Pages) provides several implicit objects that are automatically available in every JSP
page without needing any declaration. These objects help developers work easily with request data,
responses, sessions, application data, and server configurations. JSP defines nine implicit objects that
simplify web application development.
1. request Object
The request object represents the client’s HTTP request.
Type: HttpServletRequest
Uses:
Reading form data
Getting query parameters
Accessing headers and cookies
Identifying request method (GET, POST)
Example:
String name = [Link]("username");
2. response Object
The response object is used to send output back to the client.
Type: HttpServletResponse
Uses:
Redirecting pages
Setting content type
Sending cookies
Sending headers
Example:
[Link]("[Link]");
3. out Object
The out object is used to display output on the browser.
Type: JspWriter
Uses:
Printing text
Displaying variables
Writing HTML to the page
Example:
[Link]("Welcome to JSP!");
4. session Object
The session object stores data for a particular user across multiple requests.
Type: HttpSession
Uses:
Login management
User tracking
Storing user-specific data
Example:
[Link]("user", "Namita");
5. application Object
The application object stores information shared by all users of the application.
Type: ServletContext
Uses:
Sharing global data
Storing application-level settings
Initializing resources
Example:
[Link]("visitorCount", 100);
6. config Object
The config object provides configuration information for a JSP page.
Type: ServletConfig
Uses:
Accessing initialization parameters from [Link]
Reading servlet configuration
Example:
String email = [Link]("adminEmail");
7. pageContext Object
The pageContext object provides access to all JSP scopes and to all implicit objects.
Type: PageContext
Uses:
Managing attributes in page, request, session, and application scope
Forwarding request
Including other JSP pages
Example:
[Link]("[Link]");
8. page Object
The page object refers to the current JSP page instance, similar to “this” in Java.
Type: Object
Uses:
Rarely used directly
Mostly for internal reference
Example:
[Link]([Link]());
9. exception Object
The exception object is used only in JSP error pages.
Type: Throwable
Note: The page must include isErrorPage="true".
Example:
[Link]("Error: " + [Link]());
JSP Object Scopes
JSP objects may exist in different scopes:
1. page – Object exists only within the current JSP page.
2. request – Object exists for one browser request.
3. session – Object exists across multiple requests from the same user.
4. application – Object shared by all users of the application.
Summary Table of JSP Implicit Objects
request – HttpServletRequest – Handles client request data
response – HttpServletResponse – Sends output back to client
out – JspWriter – Prints content
session – HttpSession – Manages user session
application – ServletContext – Application-wide data
config – ServletConfig – Configuration for JSP
pageContext – PageContext – Access to all scopes
page – Object – Current JSP page instance
exception – Throwable – Represents errors in error pages
DECLARING VARIABLES AND METHODS IN JSP – DESCRIPTIVE NOTES
Introduction
JSP (Java Server Pages) allows embedding Java code inside HTML to create dynamic content. JSP
provides special tags, called scripting elements, for declaring variables, writing Java code, and
defining methods inside a JSP page. The three main scripting elements are: Scriptlet, Expression, and
Declaration.
This topic focuses on how to declare variables and methods using the Declaration tag in JSP.
1. Scripting Elements in JSP
JSP supports three main types of scripting elements:
a) Scriptlet Tag:
<% Java code %>
Used for writing Java statements that are executed during the request.
b) Expression Tag:
<%= expression %>
Used to output a value directly to the client.
c) Declaration Tag:
<%! declarations %>
Used to declare variables and methods at the class level.
The Declaration tag is the only one used specifically for declaring variables and methods.
2. Declaring Variables in JSP
Variables can be declared in JSP using the Declaration tag (<%! … %>).
These variables become part of the generated Servlet class as instance variables.
Syntax:
<%! datatype variableName = value; %>
Example:
<%! int count = 0; %>
This means:
• The variable “count” will be available throughout the JSP page.
• It is created only once when the JSP is translated into a Servlet.
Another example:
<%! String message = "Welcome to JSP"; %>
3. Declaring Methods in JSP
Methods can also be declared using the Declaration tag. These methods are added to the
Servlet class created from the JSP page.
Syntax:
<%!
returnType methodName(parameters) {
// method body
}
%>
Example – Method to add two numbers:
<%!
public int add(int a, int b) {
return a + b;
}
%>
Example – Method to return a greeting message:
<%!
public String greet(String name) {
return "Hello " + name;
}
%>
4. Using Declared Variables and Methods Inside JSP
A declared method can be called inside a Scriptlet or Expression.
Example:
<%!
public int square(int x) {
return x * x;
}
%>
Calling the method:
<%= square(5) %>
Output:
25
Using a declared variable:
<%! int count = 1; %>
<%= "Visitor Count: " + count %>
5. Difference Between Scriptlet and Declaration
Scriptlet (<% %>)
• Contains executable statements
• Runs inside service() method
Declaration (<%! %>)
• Contains variable or method declarations
• Added outside service() method
Example:
<% int x = 10; %> // Local variable
<%! int y = 20; %> // Instance variable
6. When to Use Declaration Tag
Use Declaration Tag when:
• You need class-level variables
• You want to reuse methods in the page
• You need helper functions for formatting, calculations, or printing data
Avoid using declarations for:
• Business logic (should be in JavaBeans or Servlet)
• Large code blocks
• Database handling (should be in DAO classes)
7. Advantages of Declaration Tag
• Reusable Java functions inside JSP
• Cleaner code compared to repeating scriptlets
• Best for simple utility functions
• Allows class-level variable sharing
8. Disadvantages of Declaration Tag
• Mixing Java code with HTML reduces readability
• Difficult to debug large JSP pages
• Not suitable for complex logic
• Modern practice encourages using Servlets, Beans, and EL instead
9. Example: Complete JSP Page Using Declarations
<html> <body> <%! int count = 0; public String greet(String name) { return "Welcome, " + name; } %>
<% count++; %>
<p>Total Visitors: <%= count %></p> <p><%= greet("Namita") %></p> </body> </html>
DEBUGGING IN JSP – DESCRIPTIVE NOTES
Introduction
Debugging in JSP (Java Server Pages) refers to the process of identifying, locating, and fixing errors
that occur during the execution of JSP pages. Since JSP is converted into a Servlet during execution,
debugging can involve both JSP-level and Servlet-level techniques. Understanding debugging tools,
server logs, JSP error pages, and common error types is essential for developing stable JSP
applications.
1. Types of Errors in JSP
1. Syntax Errors
o Occur when JSP tags or Java code inside JSP is incorrect.
o Detected at translation or compilation time.
o Example: missing semicolon, wrong tag syntax.
2. Runtime Errors
o Occur when the program executes.
o Causes include null pointer exceptions, invalid type casting, etc.
3. Logical Errors
o Code runs but produces incorrect output.
o Hardest to detect.
4. Configuration Errors
o Wrong servlet mapping, missing libraries in WEB-INF/lib, etc.
2. Techniques for Debugging JSP
a) Using JSP Error Pages
JSP allows defining custom error pages using page directives.
1. Create an error page:
<%@ page isErrorPage="true" %>
Error Occurred: <%= [Link]() %>
2. In the main JSP page:
<%@ page errorPage="[Link]" %>
The exception implicit object is available only if isErrorPage="true".
b) Using Server Logs (Tomcat Logs)
Tomcat stores log files in the logs/ directory.
Important logs:
[Link] – main server output
[Link] – application errors
[Link] – deployment issues
Logs display line numbers and stack traces which help identify exact error locations.
c) Print Debug Values Using [Link]
Helpful for checking values during execution.
Example:
<% [Link]("Value of x = " + x); %>
Not recommended for production but useful during development.
d) Java Exception Handling Inside JSP
Use try-catch block to catch code errors.
Example:
<%
try {
int result = 10 / 0;
} catch(Exception e) {
[Link]("Error: " + [Link]());
%>
e) Debugging Using IDE Tools (Eclipse, IntelliJ)
Set breakpoints in the servlet generated from JSP.
Step through code execution.
View variable values.
These tools generate the Java Servlet file from JSP, making debugging easier.
f) Enabling Development Mode in Tomcat
In [Link], use <error-page> mapping to show detailed errors.
Example:
<error-page>
<exception-type>[Link]</exception-type>
<location>/[Link]</location>
</error-page>
g) Using pageContext for Debugging
The pageContext object provides access to attributes from all scopes (page, request, session,
application).
Example:
<%= [Link]("username", PageContext.SESSION_SCOPE) %>
Useful for checking whether attributes are correctly set.
3. Common JSP Debugging Problems and Solutions
1. HTTP 404 Error (Page Not Found)
o JSP file not in correct directory
o Incorrect URL mapping
o Solution: Check folder structure and URL
2. HTTP 500 Error (Server Error)
o Syntax or runtime error in JSP
o Solution: Check logs for stack trace
3. ClassNotFoundException / NoClassDefFoundError
o Missing JAR file in WEB-INF/lib
o Solution: Add required JAR and restart
4. NullPointerException
o Accessing variables or methods without initialization
o Solution: Null checks and proper initialization
5. JDBC Connection Errors
o Wrong database URL, username, password
o Solution: Check database configuration
6. Session Timeout Issues
o Session disappears during navigation
o Solution: Increase timeout in [Link]
4. Best Practices for Debugging JSP
1. Keep business logic out of JSP (use Servlets or Beans).
2. Use JSTL and EL to reduce scriptlet errors.
3. Organize your application using MVC architecture.
4. Use meaningful error messages and custom error pages.
5. Check Tomcat logs regularly.
6. Use try-catch blocks only when necessary.
7. Test code in small parts to isolate issues.
8. Avoid printing too much debug information in production.
5. Example: Custom Error Handling
[Link]
<%@ page isErrorPage="true" %>
<h2>An error occurred:</h2>
<p><%= exception %></p>
[Link]
<%@ page errorPage="[Link]" %>
<% int x = 10 / 0; %>
Output:
Displays custom error page instead of default server error.
SHARING DATA BETWEEN JSP PAGES – DESCRIPTIVE NOTES
Introduction
In JSP (Java Server Pages), it is often necessary to pass data from one page to another. This may
happen when submitting a form, navigating between pages, maintaining user state, or displaying
results computed on a previous page. JSP provides multiple mechanisms to share data, each suitable
for different scenarios such as temporary sharing, session-wide sharing, or application-wide sharing.
Data can be shared using:
1. Request Scope
2. Session Scope
3. Application Scope
4. Hidden Fields
5. URL Rewriting
6. Cookies
7. JSP Include / Forward
8. JavaBeans
Each technique has different usage, lifetime, and purpose.
1. Sharing Data Using Request Scope
The request object allows sharing data only within a single request, usually between a JSP and
another JSP/Servlet using forward.
Setting data in request scope:
[Link]("name", "Namita");
Forwarding to another JSP:
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
Retrieving data in [Link]:
<%= [Link]("name") %>
Lifetime: Until the request completes.
Use case: Form submission, temporary data, search results.
2. Sharing Data Using Session Scope
The session object stores data for a particular user across multiple requests.
Setting session attribute:
[Link]("user", "Namita");
Retrieving in another JSP page:
<%= [Link]("user") %>
Lifetime: Until the user logs out or session timeout occurs.
Use case: Login data, shopping cart, user preferences.
3. Sharing Data Using Application Scope
The application object stores data shared by all users in the web application.
Setting application attribute:
[Link]("counter", 1);
Retrieving in another JSP:
<%= [Link]("counter") %>
Lifetime: Until the server stops or application restarts.
Use case: Visitor counter, configuration settings.
4. Sharing Data Using Hidden Form Fields
Hidden fields are HTML input fields not visible to the user, used to send additional data during form
submission.
Example in first JSP:
<input type="hidden" name="userid" value="1001">
Second JSP receives it via:
String id = [Link]("userid");
Use case: Maintaining state across pages without session.
Limitations: Visible in page source, not secure.
5. Sharing Data Using URL Rewriting
Data is appended directly to the URL.
Example:
<a href="[Link]?name=Namita&age=20">Go</a>
Retrieving:
[Link]("name");
Use case: When cookies are disabled.
Limitation: Limited data size, visible in browser.
6. Sharing Data Using Cookies
Cookies store data on the client’s browser.
Creating a cookie:
Cookie c = new Cookie("city", "Lucknow");
[Link](c);
Retrieving in another JSP:
Cookie[] cookies = [Link]();
Lifetime: Based on expiry setting; can persist across sessions.
Use case: Remember username, preferences, auto-login.
7. Sharing Data Using JSP include / forward
Using include:
<jsp:include page="[Link]" />
Shared data is accessible through request attributes.
Using forward:
<jsp:forward page="[Link]" />
Data remains in the same request scope.
8. Sharing Data Using JavaBeans
JavaBeans offer a clean method to store data and share across JSP pages.
Declaring a bean:
<jsp:useBean id="user" class="UserBean" scope="session" />
Setting value:
<jsp:setProperty name="user" property="name" value="Namita" />
Retrieving in another JSP:
<jsp:getProperty name="user" property="name" />
Use case: Best practice for MVC-based applications.
9. Comparison of Data Sharing Methods
Method Lifetime Best Use
Request Scope Single request Form handling, search results
Session Scope Entire session Login, shopping cart
Application Scope Entire application Counters, global settings
Hidden Fields One request but visible Multi-step forms
URL Rewriting Single request When cookies disabled
Cookies Client-side storage Preferences, auto login
Include/Forward Inside same request Page reuse, UI components
JavaBeans Depends on scope Clean MVC architecture