KEMBAR78
MCS-220 Assignment | PDF | Computing | Software Engineering
0% found this document useful (0 votes)
24 views51 pages

MCS-220 Assignment

The document outlines the assignment details for the Web Technologies course, including the need for design patterns, specifically the Repository Design Pattern, and the differences between JAR and WAR files. It explains the servlet interface, the lifecycle of servlets, and the advantages of Java Server Pages over servlets, along with examples of JSP components. Additionally, it provides a JSP program for generating a Fibonacci series and discusses various JSP components with code examples.

Uploaded by

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

MCS-220 Assignment

The document outlines the assignment details for the Web Technologies course, including the need for design patterns, specifically the Repository Design Pattern, and the differences between JAR and WAR files. It explains the servlet interface, the lifecycle of servlets, and the advantages of Java Server Pages over servlets, along with examples of JSP components. Additionally, it provides a JSP program for generating a Fibonacci series and discusses various JSP components with code examples.

Uploaded by

nancy james
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Course Code : MCS-220

Course Title : Web Technologies


Assignment Number : MCA_NEW(II)/220/Assign/2024-25 Maximum Marks : 100
Weightage : 30%
Last date of Submission : 31st October, 2024 (For July, 2024 Session)
15th April, 2025 (For January, 2025 Session)

1) (a) What is need of design pattern? Explain the use of Repository Design Pattern with the
help of an example.
(a) Need for Design Patterns
Design patterns are established solutions to common software design problems. They help
developers by providing templates for writing efficient, maintainable, and scalable code. The key
benefits of design patterns include:
1. Code Reusability – Encourages reusable solutions, reducing redundant work.
2. Maintainability – Makes it easier to modify and extend code.
3. Scalability – Helps structure code for future enhancements.
4. Separation of Concerns – Improves code organization by defining clear responsibilities.
5. Best Practices – Provides standardized approaches that developers can follow.

(b) Repository Design Pattern


The Repository Pattern is used to abstract the data access logic and provides a centralized way to
manage database operations. This ensures that the application logic is not directly dependent on
the database.
Why Use Repository Pattern?
• Decouples business logic from data access logic.
• Improves code maintainability and testability.
• Allows easy switching between different data sources (SQL, NoSQL, APIs).

Example: Implementing Repository Pattern in ASP.NET Core with Entity Framework Core
1. Define the Entity Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
2. Create the Repository Interface
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product GetById(int id);
void Add(Product product);
void Update(Product product);
void Delete(int id);
}
3. Implement the Repository Class
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;

public ProductRepository(ApplicationDbContext context)


{
_context = context;
}

public IEnumerable<Product> GetAll()


{
return _context.Products.ToList();
}

public Product GetById(int id)


{
return _context.Products.Find(id);
}

public void Add(Product product)


{
_context.Products.Add(product);
_context.SaveChanges();
}

public void Update(Product product)


{
_context.Products.Update(product);
_context.SaveChanges();
}

public void Delete(int id)


{
var product = _context.Products.Find(id);
if (product != null)
{
_context.Products.Remove(product);
_context.SaveChanges();
}
}
}
4. Register Repository in Dependency Injection (DI) Container
In Program.cs (for .NET 6+):
builder.Services.AddScoped<IProductRepository, ProductRepository>();
5. Use Repository in Controller
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
private readonly IProductRepository _repository;

public ProductController(IProductRepository repository)


{
_repository = repository;
}

[HttpGet]
public IActionResult GetAll()
{
return Ok(_repository.GetAll());
}

[HttpPost]
public IActionResult Create(Product product)
{
_repository.Add(product);
return CreatedAtAction(nameof(GetAll), new { id = product.Id }, product);
}
}

1) (b) What is the difference between JAR and WAR files? Describe the process of creation,
deployment and extraction of WAR files.
(b) Difference Between JAR and WAR Files

Feature JAR (Java Archive) WAR (Web Application Archive)

Used for packaging Java classes, libraries, Used for packaging Java web
Purpose
and resources. applications.

Servlets, JSP files, HTML, CSS,


.class files, metadata (MANIFEST.MF), and
Contains JavaScript, and libraries (WEB-
resource files (images, properties, etc.).
INF/lib).

Typically used for standalone Java Deployed in a Java web server (e.g.,
Deployment
applications or libraries. Tomcat, JBoss, WildFly).

Contains a structured WEB-INF folder


Structure Flat structure with compiled Java classes.
for web applications.

Can be executed directly if it contains a Main- Requires a servlet container or Java


Execution
Class in MANIFEST.MF. EE application server.

Creation, Deployment, and Extraction of WAR Files


1. Creation of WAR File
A WAR (Web Application Archive) file is created by packaging all web application components in a
structured manner.
Steps to Create a WAR File (Manually)
1. Create Project Structure
2. MyWebApp/

3. ├── WEB-INF/

4. │ ├── web.xml (Deployment descriptor)

5. │ ├── classes/ (Compiled Java classes)

6. │ ├── lib/ (JAR dependencies)

7. ├── index.jsp

8. ├── styles.css

9. ├── images/

10. Compile Java Files (if any)


11. javac -d WEB-INF/classes src/com/example/*.java
12. Create WAR File Using jar Command
13. jar -cvf MyWebApp.war *
or using Maven:
mvn package
The WAR file is generated inside target/.

2. Deployment of WAR File


A WAR file is deployed to a servlet container like Apache Tomcat, JBoss, or GlassFish.
Deployment on Tomcat
1. Copy WAR File to Tomcat’s webapps Directory
2. cp MyWebApp.war /path/to/tomcat/webapps/
3. Start Tomcat Server
4. cd /path/to/tomcat/bin
5. ./startup.sh (Linux/Mac)
6. startup.bat (Windows)
7. Access the Application in a Browser
8. http://localhost:8080/MyWebApp/

3. Extraction of WAR File


If you need to extract a WAR file to inspect or modify its contents:
Using jar Command
jar -xvf MyWebApp.war
Using unzip
unzip MyWebApp.war -d MyWebApp/

Conclusion
• JAR files are used for general Java applications and libraries.
• WAR files are used for Java web applications and contain all necessary resources for
deployment.
• A WAR file is deployed in servlet containers like Tomcat, and it can be extracted using jar or
unzip commands.

2) (a) What is Servlet interface? Differentiate between GenericServlet and HTTPServlet?


(a) Servlet Interface
The Servlet interface is the core interface in Java EE (Jakarta EE) that defines methods for
handling requests in a web server. It is part of the javax.servlet package and provides lifecycle
methods for servlets.
Key Methods of Servlet Interface
1. init(ServletConfig config) – Initializes the servlet.
2. service(ServletRequest req, ServletResponse res) – Processes client requests and
generates responses.
3. destroy() – Cleans up resources before the servlet is removed from memory.
4. getServletConfig() – Returns the servlet’s configuration object.
5. getServletInfo() – Returns information about the servlet.
To create a servlet, you can implement the Servlet interface directly, but usually, developers extend
GenericServlet or HttpServlet for convenience.

Difference Between GenericServlet and HttpServlet

Feature GenericServlet HttpServlet

Extends GenericServlet and


Implements Servlet interface and extends
Extends implements HTTP-specific
javax.servlet.GenericServlet.
functionality.

Protocol Protocol-independent (can be used for FTP, Designed specifically for HTTP
Support SMTP, etc.). requests.
Feature GenericServlet HttpServlet

Request Provides doGet(), doPost(), doPut(),


Requires overriding the service() method.
Handling doDelete(), etc.

Used for generic request handling (not HTTP- Used for web applications that
Use Case
specific). handle HTTP requests.

May be used in applications where the Used in web-based applications


Example
protocol is not strictly HTTP. running on a web server like Tomcat.

Example of GenericServlet
import java.io.*;
import javax.servlet.*;

public class MyGenericServlet extends GenericServlet {


public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Hello from GenericServlet!</h2>");
}
}

Example of HttpServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyHttpServlet extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Hello from HttpServlet!</h2>");
}
}
2) (b) Briefly explain servlet life cycle. Also, explain the request and response in the context of
HTTP?
(b) Servlet Life Cycle
The Servlet Life Cycle consists of four main phases:
1. Loading and Instantiation
o The servlet class is loaded when the server starts or upon receiving the first request.
o The servlet container creates an instance of the servlet.
2. Initialization (init())
o The init(ServletConfig config) method is called once when the servlet is first created.
o Used for one-time setup tasks (e.g., opening database connections).
3. Request Handling (service())
o The service(ServletRequest req, ServletResponse res) method handles client
requests.
o For HttpServlet, it delegates to doGet(), doPost(), doPut(), etc.
4. Destruction (destroy())
o The destroy() method is called before the servlet is removed from memory.
o Used for cleanup tasks (e.g., closing database connections).
Servlet Life Cycle Diagram
Client Request → Servlet Loaded → init() → service() (multiple times) → destroy()

Request and Response in the Context of HTTP


1. HTTP Request
A request is sent from a client (browser, mobile app, etc.) to the server. It consists of:
• Request Line – Contains the HTTP method (GET, POST, etc.), URL, and HTTP version.
• Headers – Metadata such as User-Agent, Content-Type, Cookie, etc.
• Body (Optional) – Data sent in POST, PUT, etc. (e.g., form data, JSON).
Example: HTTP GET Request
GET /hello HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Example: HTTP POST Request
POST /login HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27

username=admin&password=123

2. HTTP Response
A response is sent from the server to the client. It consists of:
• Status Line – HTTP version and status code (e.g., 200 OK, 404 Not Found).
• Headers – Metadata such as Content-Type, Set-Cookie, etc.
• Body – The actual response content (HTML, JSON, etc.).
Example: HTTP Response
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 50

<html><body><h2>Welcome to my website</h2></body></html>

Servlet Example: Handling HTTP Requests & Responses


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Hello, Servlet Handling HTTP Requests!</h2>");
}
}
• A client sends an HTTP request (GET /HelloServlet).
• The servlet processes the request and generates an HTTP response.
3) (a) Explain the advantages of Java Server Pages over the servlet. Also, write a JSP program
for Fibonacci Series.
(a) Advantages of Java Server Pages (JSP) over Servlets
Java Server Pages (JSP) is a technology used for creating dynamic web pages in Java. While
servlets are powerful, JSP offers several advantages:

Feature Servlets JSP

Requires Java coding for HTML Allows embedding Java code inside HTML,
Ease of Use
content. making it easier for UI development.

Encourages separation of presentation


Separation of Mixes business logic and
(JSP) and business logic (Java Beans,
Concerns presentation in Java code.
Servlets).

Hard to modify UI since HTML is Easier to maintain as UI and Java code are
Maintenance
inside Java code. separate.

Less readable due to HTML in More readable as HTML is primary with


Readability
Java. minimal Java code.

Requires explicit object creation Provides implicit objects like request,


Built-in Objects
(e.g., PrintWriter). response, session, out, etc.

Requires manually writing Java Supports JSP tag libraries (JSTL), making
Custom Tags
classes for reusable components. code cleaner.

When to Use JSP?


• When the primary focus is on displaying dynamic content.
• When separating presentation from logic is necessary.
• When you need faster development with HTML-based UI design.

JSP Program for Fibonacci Series


The following JSP program generates a Fibonacci Series up to n terms, where n is provided by the
user.
Code: fibonacci.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series in JSP</title>
</head>
<body>
<h2>Fibonacci Series Generator</h2>

<form method="post">
Enter number of terms: <input type="text" name="num" required>
<input type="submit" value="Generate">
</form>

<%
String numStr = request.getParameter("num");
if (numStr != null) {
int n = Integer.parseInt(numStr);
int first = 0, second = 1, next;

out.println("<h3>Fibonacci Series up to " + n + " terms:</h3>");


out.print("<p>" + first + ", " + second);

for (int i = 2; i < n; i++) {


next = first + second;
out.print(", " + next);
first = second;
second = next;
}
out.println("</p>");
}
%>
</body>
</html>

Explanation
1. HTML Form – Accepts user input (n terms).
2. JSP Scriptlet (<% %>) – Processes Fibonacci logic.
3. request.getParameter("num") – Retrieves input from the user.
4. Loop to Generate Series – Displays Fibonacci numbers dynamically.
Example Output
Input: 5
Output: 0, 1, 1, 2, 3

3) (b) Explain the various components of JSP with suitable code.


(b) Components of JSP with Examples
Java Server Pages (JSP) consists of several components that help in creating dynamic web
pages. The main components of JSP are:
1. JSP Directives
Directives provide instructions to the JSP container about how to process the page. They do not
produce any output.
Types of Directives:
• Page Directive (<%@ page %>) – Defines page-level settings.
• Include Directive (<%@ include %>) – Includes a file at compile time.
• Taglib Directive (<%@ taglib %>) – Declares a custom tag library.
Example:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="header.jsp" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2. JSP Scriptlets (<% %>)


Scriptlets contain Java code that gets executed within the JSP file.
Example:
<%
String name = "John Doe";
int age = 25;
%>
<p>Name: <%= name %></p>
<p>Age: <%= age %></p>

Note: Variables declared inside scriptlets are local to the request.

3. JSP Expressions (<%= %>)


Used to evaluate Java expressions and print the result in the output.
Example:
<%
int a = 10, b = 20;
%>
<p>Sum: <%= a + b %></p>

Equivalent to out.print(a + b);

4. JSP Declarations (<%! %>)


Used to declare variables and methods at class level (persists across requests).
Example:
<%! int counter = 0; %>

<%
counter++;
%>
<p>Page Visits: <%= counter %></p>

Unlike scriptlets, declared variables persist across requests.

5. JSP Implicit Objects


JSP provides built-in objects that can be used directly in JSP pages.

Implicit Object Description

out Prints output to the response.

request Represents HttpServletRequest (contains client request data).

response Represents HttpServletResponse (controls response).

session Represents HttpSession (stores user session data).

application Represents ServletContext (application-wide data).

config Represents ServletConfig (configuration settings).

pageContext Provides page-related information.

exception Represents an exception (used in error pages).

Example Using Implicit Objects


<p>Client IP: <%= request.getRemoteAddr() %></p>
<p>Session ID: <%= session.getId() %></p>

6. JSP Actions (<jsp:action> Tags)


JSP actions perform tasks such as including files, forwarding requests, and handling JavaBeans.
Common JSP Actions:
1. <jsp:include> – Includes a file at runtime.
2. <jsp:forward> – Forwards a request to another resource.
3. <jsp:param> – Passes parameters between pages.
4. <jsp:useBean> – Instantiates or retrieves a JavaBean.
Example of <jsp:include>
<jsp:include page="footer.jsp" />
Example of <jsp:forward>
<jsp:forward page="welcome.jsp" />
Example of JavaBean Handling
<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="Alice" />
<p>Welcome, <jsp:getProperty name="user" property="name" /></p>

4) What do you mean by JDBC? Explain how we retrieve data from database using suitable
JSP program.
What is JDBC?
JDBC (Java Database Connectivity) is a Java API that allows applications to interact with
relational databases. It provides methods for connecting to a database, executing SQL queries,
and retrieving results.
JDBC Architecture
JDBC consists of:
1. JDBC Driver – Connects Java applications to the database.
2. Connection – Establishes a connection with the database.
3. Statement – Executes SQL queries.
4. ResultSet – Stores retrieved data.

Retrieving Data from Database Using JSP & JDBC


We will create a JSP page that connects to a MySQL database, retrieves data from a table, and
displays it in an HTML table.
Step 1: Database Setup
Assume we have a MySQL database named company with a table employees:
CREATE DATABASE company;
USE company;

CREATE TABLE employees (


id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10,2)
);

INSERT INTO employees (name, department, salary) VALUES


('John Doe', 'IT', 50000),
('Alice Brown', 'HR', 45000),
('Bob Smith', 'Finance', 60000);

Step 2: Create db.jsp for Database Connection


This file establishes a JDBC connection using MySQL Driver.
<%@ page import="java.sql.*" %>
<%!
// Database connection details
String url = "jdbc:mysql://localhost:3306/company";
String user = "root"; // Change as per your MySQL username
String password = ""; // Change as per your MySQL password
Connection conn = null;

public Connection getDBConnection() {


try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load JDBC Driver
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
%>

Step 3: Create retrieve.jsp to Fetch and Display Data


<%@ page import="java.sql.*" %>
<%@ include file="db.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title>Employee List</title>
<style>
table { width: 50%; border-collapse: collapse; margin: 20px 0; }
th, td { border: 1px solid black; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>

<h2>Employee Details</h2>

<%
Connection con = getDBConnection();
String query = "SELECT * FROM employees";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
%>

<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
<%
while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("department") %></td>
<td><%= rs.getDouble("salary") %></td>
</tr>
<%
}
rs.close();
stmt.close();
con.close();
%>
</table>

</body>
</html>

Explanation
1. db.jsp establishes a connection to MySQL.
2. retrieve.jsp:
o Retrieves all employee records.
o Displays them in an HTML table.
3. JDBC Classes Used:
o DriverManager.getConnection() – Establishes a connection.
o Statement & ResultSet – Executes and retrieves query results.
o Loop (while rs.next()) – Iterates over the result set.

Example Output
Employee Details

ID Name Department Salary

1 John Doe IT 50000

2 Alice Brown HR 45000

3 Bob Smith Finance 60000

5) What are the Strut2 core components? Explain the working and flow of Struts 2 with the
help of suitable diagram.
Struts 2 Core Components
Struts 2 is a Java-based MVC framework used for developing web applications. It follows the
Model-View-Controller (MVC) design pattern and is based on Servlets and JSP.
Core Components of Struts 2
1. Action – A Java class that processes user requests and returns a result.
2. Interceptor – Pre-processing and post-processing logic applied to requests (e.g., validation,
logging).
3. Result – Determines what happens after an Action executes (e.g., forwarding to JSP).
4. Value Stack & OGNL (Object-Graph Navigation Language) – Stores data for use in JSP
pages.
5. Struts Configuration File (struts.xml) – Maps actions to their corresponding results.
6. Filter Dispatcher – The entry point for all Struts 2 requests (replaced by
StrutsPrepareAndExecuteFilter in later versions).

Working and Flow of Struts 2


Struts 2 follows a request-processing workflow that includes multiple components.
Struts 2 Request Flow:
1. Client Request: A user sends a request (e.g., clicking a button).
2. Filter Dispatcher: The StrutsPrepareAndExecuteFilter intercepts the request.
3. Action Mapping: Struts 2 checks struts.xml to determine the action.
4. Interceptor Execution: Pre-processing occurs (e.g., input validation).
5. Action Execution: The corresponding Action class processes the request.
6. Result Processing: The result (e.g., JSP page) is returned.
7. Response Sent to Client: The final output is displayed to the user.

Struts 2 Workflow Diagram


[Client]

(1) Request

[StrutsPrepareAndExecuteFilter]

(2) Action Mapping (`struts.xml`)

(3) Interceptors (Pre-processing)

(4) Action Execution

(5) Interceptors (Post-processing)

(6) Result Processing (`JSP`)

(7) Response Sent

[Client]

Example Struts 2 Application


Step 1: Define struts.xml
<struts>
<package name="default" extends="struts-default">
<action name="hello" class="com.example.HelloAction">
<result name="success">/hello.jsp</result>
</action>
</package>
</struts>

Maps /hello URL to HelloAction.java and forwards the result to hello.jsp.


Step 2: Create the Action Class (HelloAction.java)
package com.example;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {


private String message;

public String execute() {


message = "Hello, Struts 2!";
return SUCCESS; // "success" mapped to hello.jsp
}

public String getMessage() {


return message;
}
}

Step 3: Create the View (hello.jsp)


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 Example</title></head>
<body>
<h2>Message from Action: <s:property value="message"/></h2>
</body>
</html>

6) A) Explain process of creating records using Spring Boot and Hibernate.


Creating Records Using Spring Boot and Hibernate
Spring Boot simplifies the development of Java applications, and Hibernate provides ORM (Object-
Relational Mapping) to interact with databases efficiently. Below is a step-by-step guide to
creating records using Spring Boot and Hibernate.
Step 1: Setup Spring Boot Project
You can create a Spring Boot project using:
• Spring Initializr (https://start.spring.io/)
• Manually setting up dependencies in pom.xml
Dependencies (pom.xml)
Add the required dependencies for Spring Boot, Hibernate, and MySQL.
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot JPA (Includes Hibernate) -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<!-- Spring Boot Starter Test -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Step 2: Configure Database in application.properties


Inside src/main/resources/application.properties, configure the database settings:
spring.datasource.url=jdbc:mysql://localhost:3306/company
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA and Hibernate Configuration


spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Note:
• ddl-auto=update automatically creates or updates database tables.
• show-sql=true logs SQL queries in the console.

Step 3: Create Entity Class


The @Entity annotation maps a Java class to a database table.
Employee.java (Entity)
package com.example.demo.model;

import jakarta.persistence.*;

@Entity
@Table(name = "employees")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String department;
private double salary;

// Constructors
public Employee() {}

public Employee(String name, String department, double salary) {


this.name = name;
this.department = department;
this.salary = salary;
}

// Getters and Setters


public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getName() { return name; }


public void setName(String name) { this.name = name; }

public String getDepartment() { return department; }


public void setDepartment(String department) { this.department = department; }

public double getSalary() { return salary; }


public void setSalary(double salary) { this.salary = salary; }
}

Step 4: Create Repository Interface


Spring Data JPA provides JpaRepository to simplify CRUD operations.
EmployeeRepository.java
package com.example.demo.repository;

import com.example.demo.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

JpaRepository provides methods like save(), findAll(), and deleteById().

Step 5: Create Service Layer


The service layer contains business logic.
EmployeeService.java
package com.example.demo.service;

import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

@Autowired
private EmployeeRepository employeeRepository;

public Employee saveEmployee(Employee employee) {


return employeeRepository.save(employee);
}
}

Step 6: Create Controller for API Endpoints


The controller layer handles HTTP requests.
EmployeeController.java
package com.example.demo.controller;
import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

@PostMapping("/add")
public Employee addEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
}

@PostMapping("/add") allows adding new employees via a POST request.

Step 7: Test API Using Postman


POST Request to http://localhost:8080/employees/add
Request Body (JSON)
{
"name": "Alice Brown",
"department": "HR",
"salary": 50000
}

Expected Response:
{
"id": 1,
"name": "Alice Brown",
"department": "HR",
"salary": 50000
}

6) (b) Explain how testing of custom login form can be performed with the help of an
example
Testing a Custom Login Form in Spring Boot
Testing a custom login form ensures that authentication works correctly and users can log in
successfully. In Spring Boot, we can test the login functionality using JUnit, Spring Security, and
MockMvc.

Step 1: Setup Spring Boot Security


Dependencies (pom.xml)
Ensure you have the necessary dependencies for testing and security.
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Security -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Spring Boot JPA & H2 Database for Testing -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<!-- Spring Boot Testing -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- Spring Security Testing -->


<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Spring Security Test helps in testing authentication and authorization.

Step 2: Create a User Entity


package com.example.demo.model;

import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;

public User() {}

public User(String username, String password) {


this.username = username;
this.password = password;
}

// Getters and Setters


public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getUsername() { return username; }


public void setUsername(String username) { this.username = username; }

public String getPassword() { return password; }


public void setPassword(String password) { this.password = password; }
}

Step 3: Create Repository for User


package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
Step 4: Implement Spring Security Configuration
package com.example.demo.config;

import com.example.demo.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfig
uration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login").permitAll()
.anyRequest().authenticated()
)
.formLogin()
.and()
.logout();
return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}

Step 5: Create Login Controller


package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

private final UserRepository userRepository;


private final PasswordEncoder passwordEncoder;

public AuthController(UserRepository userRepository, PasswordEncoder passwordEncoder) {


this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}

@PostMapping("/register")
public String register(@RequestBody User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
return "User registered successfully!";
}
}

Step 6: Testing the Login Form


Creating the Test Class
package com.example.demo;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.servlet.MockMvc;

import static
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLog
in;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
public class LoginFormTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private UserRepository userRepository;

@Autowired
private PasswordEncoder passwordEncoder;

@BeforeEach
void setUp() {
userRepository.deleteAll(); // Clean DB before each test
User user = new User("testuser", passwordEncoder.encode("password"));
userRepository.save(user);
}

@Test
public void testSuccessfulLogin() throws Exception {
mockMvc.perform(formLogin().user("testuser").password("password"))
.andExpect(status().is3xxRedirection()) // Redirects to success page
.andExpect(redirectedUrl("/")); // Default success URL
}

@Test
public void testFailedLogin() throws Exception {
mockMvc.perform(formLogin().user("testuser").password("wrongpassword"))
.andExpect(status().is3xxRedirection()) // Redirects on failure
.andExpect(redirectedUrl("/login?error")); // Login error page
}
}

Step 7: Run the Tests


Run the test using JUnit:
mvn test

Test Output
[INFO] Running LoginFormTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.123 s
[INFO] BUILD SUCCESS

Q7: Explain how CRUD operations are mapped to SQL statements, with suitable example
CRUD (Create, Read, Update, Delete) operations correspond to the fundamental SQL operations
used to manage data in relational databases. Each CRUD operation maps to an equivalent SQL
statement.

1. CREATE (INSERT)
The CREATE operation inserts new records into a database table using the INSERT INTO
statement.
SQL Statement:
INSERT INTO employees (name, department, salary)
VALUES ('Alice Brown', 'HR', 50000);
Java Code Using Hibernate (Spring Boot)
public Employee createEmployee(Employee employee) {
return employeeRepository.save(employee);
}

Mapping:
• INSERT INTO employees (...) VALUES (...); → employeeRepository.save(employee);

2. READ (SELECT)
The READ operation retrieves data from the database using the SELECT statement.
SQL Statement:
SELECT * FROM employees WHERE id = 1;
Java Code Using Hibernate
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id).orElse(null);
}

Mapping:
• SELECT * FROM employees WHERE id = 1; → employeeRepository.findById(id)

3. UPDATE (UPDATE)
The UPDATE operation modifies existing records using the UPDATE statement.
SQL Statement:
UPDATE employees
SET salary = 60000
WHERE id = 1;
Java Code Using Hibernate
public Employee updateEmployee(Long id, Employee newDetails) {
Employee employee = employeeRepository.findById(id).orElse(null);
if (employee != null) {
employee.setSalary(newDetails.getSalary());
return employeeRepository.save(employee);
}
return null;
}

Mapping:
• UPDATE employees SET salary = 60000 WHERE id = 1; →
employeeRepository.save(employee);

4. DELETE (DELETE)
The DELETE operation removes records using the DELETE statement.
SQL Statement:
DELETE FROM employees WHERE id = 1;
Java Code Using Hibernate
public void deleteEmployee(Long id) {
employeeRepository.deleteById(id);
}

Mapping:
• DELETE FROM employees WHERE id = 1; → employeeRepository.deleteById(id)

Complete CRUD Example in Spring Boot


EmployeeController.java
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;

// CREATE Operation
@PostMapping("/add")
public Employee createEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}

// READ Operation
@GetMapping("/{id}")
public Employee getEmployee(@PathVariable Long id) {
return employeeRepository.findById(id).orElse(null);
}

// UPDATE Operation
@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee
newDetails) {
return employeeRepository.findById(id).map(employee -> {
employee.setSalary(newDetails.getSalary());
return employeeRepository.save(employee);
}).orElse(null);
}

// DELETE Operation
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable Long id) {
employeeRepository.deleteById(id);
}
}
Summary

CRUD
SQL Statement Hibernate (Spring Boot)
Operation

INSERT INTO employees (...) VALUES


CREATE employeeRepository.save(employee);
(...);

SELECT * FROM employees WHERE id =


READ employeeRepository.findById(id);
?;

UPDATE employees SET ... WHERE id =


UPDATE employeeRepository.save(employee);
?;

DELETE DELETE FROM employees WHERE id = ?; employeeRepository.deleteById(id);

Q8: (a) Write the unit test case to execute it as a user with RequestPostProcessor for the URL
pattern “/” which returns model attribute with key as “message” and value as “Hello World”.
Unit Test Using RequestPostProcessor in Spring Boot
In this test case, we will simulate a request to the "/" URL as an authenticated user and verify that
the response contains a model attribute with key "message" and value "Hello World".

1. Setup Spring Boot Application


Controller (HomeController.java)
We define a simple controller that returns "Hello World" in the model.
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello World");
return "home"; // This refers to home.html or a Thymeleaf template
}
}

2. Write the Unit Test Case


We use MockMvc and RequestPostProcessor to simulate a user making a request.
Test Case (HomeControllerTest.java)
package com.example.demo;

import com.example.demo.controller.HomeController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessor
s;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;


import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(HomeController.class)
public class HomeControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testHomeAsUser() throws Exception {
mockMvc.perform(get("/")
.with(SecurityMockMvcRequestPostProcessors.user("testuser"))) // Simulate user
authentication
.andExpect(status().isOk()) // Ensure HTTP 200 response
.andExpect(model().attribute("message", "Hello World")) // Validate model attribute
.andExpect(view().name("home")); // Check returned view name
}
}

3. Explanation
• mockMvc.perform(get("/")) → Simulates a GET request to /.
• .with(SecurityMockMvcRequestPostProcessors.user("testuser")) → Simulates an
authenticated user.
• .andExpect(status().isOk()) → Verifies that the request was successful (200 OK).
• .andExpect(model().attribute("message", "Hello World")) → Checks that the model
contains the expected attribute.
• .andExpect(view().name("home")) → Ensures that the view name is home.

4. Running the Test


Run the test using:
mvn test

Expected Output
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.123 s
[INFO] BUILD SUCCESS

Q8: (b) What is Role-based Login? Explain how user’s access can be restricted using Role-based
Login.
Role-Based Login in Spring Security
What is Role-Based Login?
Role-Based Login is a security mechanism where users are assigned roles (e.g., Admin, User,
Manager) and access is granted based on their assigned roles. This ensures that only authorized
users can access specific parts of the application.

Example:
• Admin can access /admin
• User can access /user
• Both can access /home

How to Implement Role-Based Login in Spring Boot?


Step 1: Add Dependencies (pom.xml)
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Security -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Spring Boot JPA & H2 Database for Testing -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<!-- Spring Boot Thymeleaf (Optional for UI) -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>

Step 2: Create the User Entity with Roles


package com.example.demo.model;
import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String username;


private String password;
private String role; // ADMIN or USER

public User() {}

public User(String username, String password, String role) {


this.username = username;
this.password = password;
this.role = role;
}

// Getters and Setters


}

Step 3: Create a Repository to Fetch Users


package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}

Step 4: Implement Custom UserDetailsService


package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class CustomUserDetailsService implements UserDetailsService {

private final UserRepository userRepository;

public CustomUserDetailsService(UserRepository userRepository) {


this.userRepository = userRepository;
}

@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
Collections.singleton(new SimpleGrantedAuthority("ROLE_" + user.getRole()))
);
}
}

This loads user details from the database and assigns roles prefixed with "ROLE_".

Step 5: Configure Security to Restrict Access


package com.example.demo.config;

import com.example.demo.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import
org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfig
uration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN") // Only Admin
.requestMatchers("/user/**").hasRole("USER") // Only User
.requestMatchers("/home").permitAll() // Everyone
.anyRequest().authenticated()
)
.formLogin()
.and()
.logout();
return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}

Key Features:
✔ /admin/** → Accessible only by Admin
✔ /user/** → Accessible only by User
✔ /home → Public (No login required)
✔ BCryptPasswordEncoder is used for password security.

Step 6: Create Role-Based Controllers


Home Controller
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

@GetMapping("/home")
public String home() {
return "home"; // View for everyone
}
}
Admin Controller
package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminController {

@GetMapping
public String adminDashboard() {
return "Welcome, Admin!";
}
}
User Controller
package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping
public String userDashboard() {
return "Welcome, User!";
}
}

Step 7: Insert Users into Database


We add users manually in the H2 Database (for testing).
INSERT INTO users (username, password, role) VALUES ('admin', '$2a$10$abcd...', 'ADMIN');
INSERT INTO users (username, password, role) VALUES ('user', '$2a$10$xyz...', 'USER');

Passwords should be hashed using BCrypt.

Step 8: Testing Role-Based Access

URL Role Required Expected Output

/home Everyone Accessible

/admin Admin Only "Welcome, Admin!"

/user User Only "Welcome, User!"

/admin (as User) Forbidden 403 Forbidden

/user (as Admin) Forbidden 403 Forbidden

Login as Admin → Access /admin


Login as User → Access /user
Unauthorized Users get 403 Forbidden

Q9: Write short notes on the following:


(a) JSP Standard Tag Library (JSTL)
(a) JSP Standard Tag Library (JSTL)
What is JSTL?
JSP Standard Tag Library (JSTL) is a collection of reusable JSP tags that simplify the
development of JavaServer Pages (JSP) by reducing the need for Java code (scriptlets) inside JSP
files. JSTL provides a standard way to handle common web development tasks like iteration,
conditionals, database access, and internationalization.
Key Features of JSTL
1. Reduces Java Code in JSP – Encourages cleaner, more readable JSP pages.
2. Encapsulates Common Tasks – Provides built-in tags for iteration, conditionals, and
formatting.
3. Improves Maintainability – Separates Java logic from presentation.

JSTL Tag Libraries


JSTL is divided into several functional tag libraries:

JSTL Library Prefix Description

Core c Flow control, iteration, conditionals, variable support.

Formatting fmt Formatting numbers, dates, currencies, and internationalization.

SQL sql Database operations (Not recommended in real-world applications).

Functions fn String manipulation functions.

XML x Processing XML data within JSP.

Example Usage of JSTL


1. Core Tags (c): Looping & Conditionals
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:set var="name" value="John Doe" />


Hello, <c:out value="${name}" />!

<c:if test="${name == 'John Doe'}">


<p>Welcome, John!</p>
</c:if>

<c:forEach var="i" begin="1" end="5">


<p>Number: ${i}</p>
</c:forEach>
2. Formatting Tags (fmt): Formatting Dates & Currency
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<fmt:setLocale value="en_US"/>
<p>Today's Date: <fmt:formatDate value="${currentDate}" pattern="dd-MM-yyyy" /></p>

<fmt:formatNumber value="12345.67" type="currency" />


3. SQL Tags (sql): Querying a Database

SQL tags should only be used for quick prototyping, not in production applications!
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<sql:setDataSource var="db" driver="com.mysql.cj.jdbc.Driver"


url="jdbc:mysql://localhost:3306/mydb"
user="root" password="password"/>

<sql:query var="result" dataSource="${db}">


SELECT * FROM users;
</sql:query>

<c:forEach var="row" items="${result.rows}">


<p>User: ${row.username}</p>
</c:forEach>
4. Function Tags (fn): String Operations
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<p>Uppercase: ${fn:toUpperCase('hello world')}</p>


<p>String Length: ${fn:length('Hello')}</p>

Advantages of JSTL

✔ Simplifies JSP Code – Reduces the need for scriptlets (<% %>) in JSP.
✔ Reusable & Standardized – Uses standard tags instead of custom logic.
✔ Improves Readability – Clean HTML-like syntax.
✔ Faster Development – Eliminates redundant Java code for common tasks.

(b) Spring Framework


Spring is a powerful Java framework used to develop enterprise applications. It provides
comprehensive infrastructure support for Java applications and simplifies dependency
management, security, and transaction handling.

Key Features of Spring Framework


1. Dependency Injection (DI) – Manages object dependencies automatically.
2. Aspect-Oriented Programming (AOP) – Separates cross-cutting concerns like logging and
security.
3. Spring MVC – A framework for building web applications.
4. Spring Boot – Simplifies Spring applications with auto-configuration.
5. Spring Data – Simplifies database access with JPA, JDBC, and NoSQL.
6. Spring Security – Provides authentication and authorization.
7. Spring Cloud – Supports microservices and cloud-based applications.

Spring Framework Architecture


Spring follows a modular architecture, meaning you can use only the components you need.
Core Modules

Module Description

Spring Core Provides Dependency Injection (DI) and BeanFactory.

Spring AOP Supports Aspect-Oriented Programming (AOP).

Spring Data Helps interact with databases easily using JPA, Hibernate, etc.

Spring MVC Framework for web applications using Model-View-Controller.

Spring Boot Provides auto-configuration to simplify Spring applications.

Spring Security Provides authentication and authorization.

Spring Cloud Helps in developing distributed microservices.

How Spring Works?


1. Bean Configuration – Define objects (beans) using XML, Java-based configuration, or
annotations.
2. Dependency Injection (DI) – Spring injects dependencies automatically.
3. ApplicationContext – Manages the entire lifecycle of beans.
4. AOP (Aspect-Oriented Programming) – Used for cross-cutting concerns (e.g., logging,
security).
5. Spring Boot (Optional) – Simplifies application setup with embedded servers.

Advantages of Spring Framework

✔ Lightweight & Modular – Use only the modules you need.


✔ Dependency Injection (DI) – Reduces manual object creation.
✔ Supports Multiple Technologies – Works with Hibernate, JPA, JMS, etc.
✔ AOP Support – Handles logging, security, and transactions efficiently.
✔ Built-in Security – Provides authentication and role-based access.
✔ Microservices Ready – Spring Boot & Spring Cloud enable microservices development.

(c) Cross Site Request Forgery (CSRF)


Cross-Site Request Forgery (CSRF) is a web security attack where a malicious website tricks a
user into unknowingly submitting a request to a different website where they are already
authenticated. This can result in unauthorized actions such as:
Changing account passwords
Transferring funds
Submitting forms without user consent

Example Scenario:
1. A user logs into their banking website (examplebank.com).
2. The user visits a malicious site (hacker.com) in another tab.
3. The malicious site has a hidden request:
4. <img src="https://examplebank.com/transfer?amount=1000&to=attacker_account">
5. Since the user is already logged in, their session cookies are automatically sent, and the
bank processes the fraudulent request.

How CSRF Works?


1. Victim logs into a trusted website (e.g., bank, social media).
2. Victim visits a malicious website that contains a hidden request.
3. Browser sends the request using stored authentication cookies (without the user's
knowledge).
4. The trusted website processes the request as if it were made by the user.

How to Prevent CSRF?

1. Use CSRF Tokens (Best Practice)


A CSRF token is a unique, random value sent with each form submission to verify that the
request comes from a legitimate source.
How it works:
• The server generates a unique token per session.
• The token is added to every form request as a hidden field.
• The server validates the token before processing the request.

Spring Security CSRF Protection Example


@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // Enable
CSRF protection
.and()
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.formLogin();
return http.build();
}
}

Spring Security automatically generates and validates CSRF tokens when enabled.

2. Use SameSite Cookies


Setting the SameSite attribute on cookies prevents them from being sent with cross-site
requests.
@Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setSameSite("Strict");
return serializer;
}

This prevents cookies from being sent in CSRF attacks.


3. Use HTTP Headers for Authentication
Instead of relying on session cookies, use tokens like JWT (JSON Web Token) or OAuth tokens in
request headers.
@RequestMapping("/api")
public ResponseEntity<String> secureApi(@RequestHeader("Authorization") String token) {
// Validate JWT token before processing request
return ResponseEntity.ok("Authenticated API Call");
}

Tokens are not automatically sent in requests like cookies, reducing CSRF risk.

4. Require User Confirmation for Critical Actions


For sensitive actions (e.g., money transfers, password changes), require re-authentication or an
OTP (One-Time Password).

Example: "Are you sure you want to transfer $1000?"

You might also like