0% found this document useful (0 votes)
7 views21 pages

JSP Basics: Dynamic Content & Session Tracking

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

JSP Basics: Dynamic Content & Session Tracking

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT 2

 JSP(java server page)

<html>

<body>

<h2>Welcome to JSP!</h2>

<%

String name = "Prashant";

[Link]("Hello, " + name);

%>

</body>

</html>

Here are some simple advantages of JSP over Servlets:


1. JSP allows you to write HTML and Java code together, making it easier to create and maintain web
pages.

2. It separates presentation (HTML) from business logic (Java) better than Servlets.

3. JSP pages are easier to write and understand for web designers since they mainly contain HTML.

4. Automatic conversion of JSP to Servlet happens behind the scenes, so you get the benefits of Servlets
without writing complex Java code.

5. Supports custom tags and Expression Language (EL), which makes coding cleaner and faster.
 architecture of JSP, and explain how it works with web servers to
generate dynamic web content.
1. Client Request

 A client (usually a web browser) sends an HTTP request to the web server for a JSP page, e.g.,
[Link]

2. JSP Engine in Web Server

 The web server forwards this request to the JSP Engine (part of the servlet container like Apache
Tomcat).
 The JSP engine checks if the JSP page has been compiled into a servlet:

o If not compiled or the JSP page is updated, the JSP engine converts the JSP page into a Java
servlet source file.

o Then, it compiles the servlet into a .class file (bytecode).

3. Servlet Lifecycle

 After compilation, the servlet lifecycle begins:

o Initialization: The servlet’s init() method is called.

o Request Processing: The service() method executes, internally calling doGet() or doPost()
methods.

o During this, the Java code inside the JSP is executed to generate dynamic content.

4. Response Generation

 The servlet generates dynamic content, typically HTML, based on the JSP’s embedded Java code and
sends it as an HTTP response back to the client.

5. Client Receives Response

 The client’s browser receives the HTML response and renders the web page dynamically.

How JSP Generates Dynamic Content

 JSP pages contain HTML and Java code.

 When the servlet executes, the Java code runs to access databases, process user inputs, or perform
business logic.

 The servlet outputs the result as HTML, which can change dynamically based on user input or
backend data.
 Compare and contrast JSP scriptlet, expression, and directive tags, and
discuss the advantages and disadvantages of using each
 What is JSP API?
 The JSP API is a set of Java interfaces and classes provided by the Java EE platform that help in building
JSP pages.

 It defines the core functionality needed to create, execute, and manage JSP pages.

 The API works closely with the Servlet API because every JSP is eventually converted into a servlet.

What is Session Tracking?


 Session tracking is a way to maintain user data (state) across multiple requests in a web application.

 HTTP is stateless, so session tracking helps remember user info (like login, preferences) during the
visit.

How is Session Tracking done in JSP?

JSP provides built-in support for sessions through the HttpSession object.

Session Tracking Techniques in JSP


1. Cookies
 Small data stored on the client’s browser.

 Server sends a cookie with response; browser sends it back with requests.

 Used to identify users or store preferences.

 Advantage: Easy, automatic once set.

 Disadvantage: Users can disable cookies; limited size.

2. URL Rewriting
 Session ID appended to the URL as a query string.

 Example: [Link]

 Works even if cookies are disabled.

 Advantage: Works without cookies.

 Disadvantage: URL looks ugly, user can share URLs exposing session ID.

3. Hidden Form Fields


 Session data or ID stored in hidden input fields inside HTML forms.

 Data sent back to the server on form submission.

 Advantage: Useful when navigation is mostly via forms.


 Disadvantage: Only works with form submissions, not direct URL access.

4. HttpSession Object
 Server-side session object created per user.

 Stores session data in server memory.

 Session ID sent to client via cookie or URL rewriting.

 Most common and easiest method in JSP.

 Use: HttpSession session = [Link]();

 Advantage: Secure and easy to use.

 Disadvantage: Uses server memory; sessions expire after timeout.

 What are Implicit Objects in JSP?


 Implicit objects are predefined objects available by default in every JSP page.

 They provide access to important information and functionality without explicitly declaring or creating
them.

 These objects simplify JSP programming by providing easy access to request, response, session,
application, etc.

Example:-

<%

String username = [Link]("username");


%>

<p>Hello, <%= username %></p>

<p>Your session ID is: <%= [Link]() %></p>

<p>Current application path: <%= [Link]("/") %></p>

✅ What is an Error in JSP?

In JSP (JavaServer Pages), an error refers to any issue or exception that occurs during the compilation,
execution, or processing of a JSP file. These errors can be caused by syntax issues, null values, bad logic, or
invalid user inputs.

🧩 Types of Errors in JSP:

Type Description

Compilation Error JSP is translated to a servlet; errors in Java code (like syntax errors) show up here.

Runtime Error Errors that occur while the page is executing, such as NullPointerException.

Logical Error Incorrect logic that doesn't throw errors but gives wrong output.

🌱 What is the Spring Framework?

The Spring Framework is a powerful, lightweight, and open-source Java framework used to build
enterprise-level applications. It simplifies Java development by providing features for

🔧 Key Features of Spring:

Feature Description

Dependency Injection Automatically manages object dependencies (Inversion of Control).

Spring MVC Builds flexible and powerful web applications.

Spring Boot Makes Spring setup and development faster and easier.

Spring Security Adds authentication and authorization features.

Spring Data Simplifies data access (JPA, MongoDB, etc.).

🚀 Why Use Spring?

 Reduces boilerplate code

 Encourages modular, testable, and maintainable code

 Integrates easily with other frameworks and technologies (Hibernate, JPA, etc.)

 Widely used for web applications and RESTful APIs


✅ Advantages of Spring Framework

1. Lightweight

o Core Spring is very lightweight in terms of size and overhead.

2. Dependency Injection (DI)

o Manages object dependencies automatically, reducing boilerplate code.

3. Modular

o You can use only the parts you need (e.g., Spring MVC, Spring JDBC).

4. Easy Integration

o Integrates well with other frameworks like Hibernate, JPA, Struts, etc.

5. Built-in MVC Framework

o Spring MVC makes it easy to build clean and maintainable web applications.

6. Support for AOP (Aspect-Oriented Programming)

o Separates cross-cutting concerns like logging, security, etc.

7. Testability

o Makes unit testing easy with loosely coupled code and mockable components.

8. Spring Boot

o Rapid development with embedded servers, auto-configuration, and less XML.

9. Security Support

o Spring Security provides a powerful and customizable authentication and authorization


system.

10. Community and Documentation

o Large community support and rich documentation.


🌱 Core Components of Spring Framework

Component Description

1. Spring Provides fundamental features like Dependency Injection (DI) and BeanFactory for
Core managing objects (beans).

2. Spring Supports Aspect-Oriented Programming, used to separate cross-cutting concerns like


AOP logging, security, etc.

A robust web framework to build web applications


Spring Web (MVC)
following MVC architecture.

7. Spring Web Flow Manages complex user workflows in web applications.

8. Spring Security Adds authentication, authorization, and access control to applications.

9. Spring A tool for rapid development, with features like auto-configuration, embedded servers,
Boot and minimal setup.

10. Spring Data Simplifies database operations, especially with JPA and NoSQL (like MongoDB).

11. Spring Test Provides support for testing Spring components using JUnit/TestNG easily.

✅ What is Dependency Injection in Spring Framework?

Dependency Injection (DI) is a design pattern used by Spring to manage object dependencies
automatically, instead of creating them manually inside classes.

🧠 Simple Definition:

Dependency Injection is a process where objects receive their dependencies from an external source (like
a configuration file or Spring container), rather than creating them themselves.
💡 Why Use DI?

 Reduces tight coupling between classes

 Improves testability and flexibility

 Promotes cleaner, maintainable code

📦 Types of Dependency Injection in Spring

Type Description

Constructor Injection Dependencies are passed via the constructor.

Setter Injection Dependencies are injected using setter methods.

Field Injection (less common) Dependencies are injected directly into fields (via @Autowired).

✅ What is BeanFactory?

 BeanFactory is the basic container in Spring.

 It lazily loads beans (creates beans only when needed).

 Suitable for simple or memory-constrained applications.


✅ What is ApplicationContext?

 ApplicationContext is the advanced container.

 It eagerly loads all beans at startup.

 Supports:

o Internationalization

o Event propagation

o Bean lifecycle callbacks

o Annotation-based configurations

🆚 Difference Table:

Feature BeanFactory ApplicationContext

Bean Loading Lazy (on demand) Eager (at startup)

Performance Slightly better for small apps Best for full-fledged Spring applications

Features Basic Dependency Injection Advanced (events, AOP, annotations)

Usage Rarely used now Common and preferred

✅ Importance of Spring Bean Configuration File

The Spring bean configuration file (usually named [Link]) is a core part of the Spring Framework. It
tells the Spring container what objects to create, how to configure them, and how they relate to each
other.

🔍 Key Importance:

1. Centralized Configuration
📌 All bean definitions and dependencies are declared in one place.

2. Dependency Injection Support


🔄 Helps in injecting dependencies between objects (Constructor, Setter, Collection).

3. Loose Coupling
🔗 Promotes loose coupling between components, improving flexibility and maintainability.

4. Easy to Manage and Modify


✏️You can change bean configurations without touching Java code.
5. Object Lifecycle Management
⏳ Spring manages the lifecycle (creation, initialization, destruction) of beans.

6. Support for Collections and References


📚 Easily inject Lists, Sets, Maps, and references to other beans.

7. Promotes Reusability
🔄 Same bean can be reused in different parts of the application.

✅ What is Component Scanning?

Component Scanning is a Spring feature that automatically detects and registers beans (classes annotated
with @Component, @Service, @Repository, or @Controller) without needing XML <bean> entries.

✅ Key Annotations for Auto Scanning

Annotation Purpose

@Component Generic bean component

@Service For service layer classes

@Repository For DAO (Data Access) classes

@Controller For web controllers (Spring MVC)


🆚 Difference: XML vs Annotation in Spring

Feature XML Configuration Annotation-Based Configuration

Style Declarative (separate XML file) Declarative (in-code using annotations)

@Component, @Service, @Repository,


Bean Declaration <bean> tag
@Controller

Dependency <property> or autowire


@Autowired, @Value, @Resource
Injection attribute

Configuration [Link] @Configuration + @ComponentScan

More flexible for external


Flexibility Easy and readable, good for smaller apps
configuration

Better for large enterprise


Maintainability Better for modular, annotation-heavy apps
applications

✅ What is Spring XML Configuration?

Spring XML Configuration is the traditional way to define beans and configure dependencies using an XML
file (usually named [Link] or [Link]). Spring reads this file to create and manage
objects (beans).

✅ Advantages of XML Configuration

 Centralized bean definitions.

 Easy to manage in large projects.

 Supports complex wiring and configuration.


 Decouples configuration from Java code.

1. Describe Dispatcher Servlet and Its Role with Example (CO4)

DispatcherServlet is the front controller in the Spring MVC framework. It acts as the central point for
handling all HTTP requests and responses in a web application.

🔁 Role of DispatcherServlet:

1. Receives Request: It intercepts all incoming HTTP requests.

2. Delegates to Handlers: Finds the appropriate controller using HandlerMapping.

3. Executes Controller Logic: Calls the controller method to process the request.

4. Returns Model and View: Gets data (model) and view name from the controller.

5. Resolves View: Uses ViewResolver to map the view name to an actual view page (like JSP, Thymeleaf).

6. Generates Response: Sends the final HTML response back to the browser.

When user hits [Link] the DispatcherServlet:

 Receives the request /hello

 Calls sayHello() method in HelloController

 Passes the model with message = "Hello Prashant!"

 Resolves the view [Link] and returns it as a response

2. Define Spring Boot, Its Features, Advantages, and Limitations

✅ Definition of Spring Boot:

Spring Boot is a framework built on top of Spring that simplifies the development of standalone,
production-ready Spring applications with minimal configuration.
🔧 Key Features of Spring Boot:

1. Auto Configuration: Automatically configures Spring components.

2. Starter Dependencies: Easy inclusion of required libraries using spring-boot-starter-*.

3. Embedded Servers: Comes with Tomcat/Jetty so no need to deploy WAR files.

4. Spring Boot CLI: Command-line tool to quickly run Spring Boot apps.

5. Production-Ready: Built-in health checks, metrics, and monitoring via Actuator.

✅ Advantages of Spring Boot:

 🚀 Fast development with minimal setup

 🧰 Less boilerplate code and XML configuration

 📦 Embedded server reduces deployment hassle

 🔍 Easy to test and debug

 ⚙️Microservice-ready with REST APIs support

❌ Limitations of Spring Boot:

 ⚖️Less flexibility compared to full Spring framework for large, complex apps

 🐘 Auto-configuration can include unnecessary dependencies

 🔐 Can be difficult to debug auto-configured behaviors

 🧠 Learning curve for deep customization

 Spring Boot CRUD operation.


CRUD stands for:

 C – Create

 R – Read

 U – Update

 D – Delete

In Spring Boot, CRUD operations are used to perform basic database operations on entities (like
Student, Product, Employee) using Spring Data JPA and REST APIs.

Spring Boot + Spring Data JPA makes it very easy to build full RESTful services with just a few lines of
code.
 JPA - Architecture
JPA (Java Persistence API, sometimes also referred to as Jakarta Persistence API) is a tool to connect
Java applications with databases for optimizing memory storage for data, thus providing a smoother
User Experience (UX). In simple terms, JPA simplifies database access from within the Java application,
by allowing to work with objects rather than SQL statements. JPA allows working with POJOs (Plain Old
Java Objects) right from desktop apps, providing developers with an ORM (Object Relational
Mapping) facility for managing relational data.

Architecture of JPA

JPA has 6 layers in its class-level architecture:

1. Entity
2. Persistence Unit

3. EntityManager

4. EntityManagerFactory

5. Query Language

6. Database Layer

Diagrammatic Representation of the Layers in JPA Class-level Architecture:

🧱 Core Classes and Interfaces of JPA

1. EntityManagerFactory

 Used to create EntityManager instances.

 Heavyweight; usually created once per application.

 Created using [Link]("unitName").

2. EntityManager

 Main interface for performing CRUD operations.

 Manages entity lifecycle.


 Methods: persist(), find(), merge(), remove(), createQuery().

3. EntityTransaction

 Used to manage transactions manually.

 Needed when not using Spring Boot or container-managed transactions.

 Methods: begin(), commit(), rollback().

4. Persistence

 A helper class to bootstrap JPA.

 It provides the method:

java

CopyEdit

EntityManagerFactory emf = [Link]("myPU");

5. Query

 Interface to create JPQL or native SQL queries.

 Methods: createQuery(), getResultList(), setParameter().

6. @Entity

 Annotation to declare a class as a JPA entity (table).

 Represents a row in a database.

7. @Table, @Id, @GeneratedValue

 Used to define table name, primary key, and ID generation strategy.

You might also like