FSD-mid 2
FSD-mid 2
React Redux is a predictable state management library specifically designed for React
applications. It allows you to centralize the application state in a single store, making it easier
to manage and debug complex applications. Redux’s main concept is to have a single source
of truth—the store—where all states are managed centrally rather than having them
distributed across different components.
1. Actions:
javascript
// actions.js
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
2. Reducer:
javascript
// reducer.js
const counterReducer = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
};
export default counterReducer;
3. Store:
javascript
// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';
javascript
// CounterComponent.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from './actions';
return (
<div>
<h1>{count}</h1>
<button onClick={() =>
dispatch(increment())}>Increment</button>
<button onClick={() =>
dispatch(decrement())}>Decrement</button>
</div>
);
};
export default CounterComponent;
1. Setup: Use libraries like Axios or the native fetch API in React.
2. API Call in Component:
o Place the HTTP request inside useEffect for lifecycle management.
o Use async/await or .then() for handling promises.
Example:
javascript
// ExampleComponent.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => console.error(error));
}, []);
return (
<div>
<h1>Data from Server:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default ExampleComponent;
React is a popular JavaScript library developed by Facebook, known for building user
interfaces (UIs) efficiently, especially for single-page applications (SPAs). Key features
include:
1. Virtual DOM: React maintains a lightweight representation of the real DOM, allowing
efficient updates by only re-rendering components that have changed.
2. JSX: JavaScript XML syntax that allows HTML-like code to be written directly in JavaScript,
making the code more readable and easier to debug.
3. Component-Based Architecture: Breaks the UI into reusable components, each with its own
logic, reducing repetition and complexity.
4. One-Way Data Binding: The data flow in React is unidirectional, simplifying the debugging
process.
5. Performance Optimization: React’s reconciliation process, along with the virtual DOM,
provides optimized and faster rendering of UIs.
2B. Illustrate the Purpose of React Router in SPA (Single Page Application)
and Provide Example Navigation
React Router is a standard library for routing in React applications. In a SPA, React Router
helps create a multi-page feel by allowing users to navigate between different components
without reloading the page.
1. Setup Routes:
javascript
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-
dom';
import Home from './Home';
import About from './About';
javascript
// Navigation.js
import React from 'react';
import { Link } from 'react-router-dom';
• public/: Contains static assets like index.html, which serves as the single page where
React is rendered.
• src/: Houses the core of the application:
o App.js: The root component that contains the main structure of the app.
o index.js: The entry point where ReactDOM.render() mounts the app on the root
HTML element.
o components/: Folder for all reusable React components.
o services/: Manages API calls and server communication.
o store/: If using Redux, this folder stores actions, reducers, and configurations.
o styles/: Contains CSS files for styling.
1. Function Components:
o Simple JavaScript functions that return JSX.
o Can use hooks like useState and useEffect for managing state and lifecycle.
o Preferred for their simplicity and performance efficiency.
javascript
function Greeting() {
return <h1>Hello, World!</h1>;
}
2. Class Components:
o ES6 classes extending React.Component.
o Use this.state for state management and lifecycle methods like
componentDidMount for side effects.
o Less commonly used in modern React since functional components with hooks cover
most needs.
javascript
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
UNIT-2
Spring Web MVC is a part of the Spring framework that follows the Model-View-Controller
(MVC) pattern to develop web applications. Here’s a simple example:
1. Controller:
java
@Controller
public class HomeController {
@RequestMapping("/home")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!");
return "home"; // This will resolve to home.jsp or home.html
}
}
2. View Configuration:
o Use a view resolver to map views (like JSP or Thymeleaf templates) for
rendering.
3. Run the Application:
o Access /home to see the controller output displayed on the specified view.
java
// Service Class
@Service
public class GreetingService {
public String greet() {
return "Hello, Spring!";
}
}
// Controller Class
@Controller
public class GreetingController {
@Autowired
private GreetingService greetingService;
@RequestMapping("/greet")
public String greet(Model model) {
model.addAttribute("message", greetingService.greet());
return "greet";
}
}
1. Encapsulation: Groups related data and methods within classes, protecting data from
outside access.
2. Inheritance: Allows a class to inherit properties and methods from another class,
supporting code reuse.
3. Polymorphism: Enables a single method to perform different behaviors (method
overloading and overriding).
4. Abstraction: Hides complex details from the user, exposing only the necessary parts
of an object.
The Spring Framework is a popular, open-source framework for building Java applications.
It provides a comprehensive programming and configuration model. Advantages include:
java
@Controller
public class WelcomeController {
@RequestMapping("/welcome")
public String welcome(Model model) {
model.addAttribute("message", "Welcome to Spring MVC using
Maven!");
return "welcome";
}
}
java
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable int id) {
return new User(id, "John Doe", "[email protected]");
}
}
This simple REST API endpoint shows how to retrieve user details via a GET request.
UNIT-3
1. a) Write a Program to Insert a Record Using Spring JDBC
Spring JDBC simplifies database interactions by providing a JdbcTemplate class that makes
it easy to connect to a database and execute SQL commands. Here’s a sample code for
inserting a record into an Employee table using Spring JDBC:
java
import org.springframework.jdbc.core.JdbcTemplate;
In this example:
DDL (Data Definition Language) queries define, modify, or remove database structures.
DDL commands include CREATE, ALTER, DROP, and TRUNCATE.
Example of DDL:
sql
In this example:
• The CREATE TABLE command defines an Employee table with columns id, name, and
department.
DDL commands do not affect data directly; they manipulate the schema of the database.
Cloud computing offers various deployment models based on organizational needs and data
sensitivity. The main deployment models are:
• Public Cloud: Operated by third-party providers (e.g., AWS, Azure). Multiple clients
share resources on demand. Public clouds are cost-effective and scalable, suitable for
non-sensitive data and applications.
• Private Cloud: Exclusive for a single organization, either hosted on-premises or by a
third party. Private clouds provide higher control and security, suitable for
organizations handling sensitive data.
• Hybrid Cloud: Combines public and private clouds to balance scalability, security,
and cost. Data flows between private and public clouds as needed, making it versatile
and flexible.
• Data Storage and Backup: Services like Google Drive and Dropbox allow users to
store, access, and share data remotely.
• Big Data Analytics: Companies like Netflix leverage cloud computing for analyzing
large datasets, supporting features like content recommendations.
• Healthcare: Cloud-based platforms store and manage patient data securely, aiding in
efficient healthcare delivery and data analysis.
java
In SQL, commands are categorized based on their functionalities. Three major categories are
DDL (Data Definition Language), DCL (Data Control Language), and TCL (Transaction
Control Language). Each serves a unique purpose in managing data and databases.
DDL commands are used to define and modify the structure of database objects like tables,
indexes, and schemas. Common DDL commands include CREATE, ALTER, DROP, and
TRUNCATE.
sql
This command creates an Employee table with three fields: id, name, and
department.
sql
This removes the Employee table and all its data from the database.
• TRUNCATE: Deletes all records in a table without removing the table itself.
sql
This command clears all data from the Employee table but keeps the table structure
intact.
DCL commands manage access rights and permissions within a database. The two main DCL
commands are GRANT and REVOKE.
sql
This grants SELECT and INSERT privileges on the Employee table to the specified user.
sql
This removes the INSERT privilege on the Employee table from the specified user.
TCL commands control transactions, ensuring data integrity in multi-step operations. The
primary TCL commands are COMMIT, ROLLBACK, and SAVEPOINT.
sql
COMMIT;
This command is issued after a series of DML commands to save all changes made
within the transaction.
• ROLLBACK: Reverts changes made in the current transaction to the last commit
point.
sql
ROLLBACK;
This undoes all changes made since the last COMMIT or SAVEPOINT, restoring data to a
previous state.
sql
SAVEPOINT savepoint1;
After a SAVEPOINT, you can use ROLLBACK TO savepoint1 to undo changes back to
that specific point without affecting earlier transactions.
Spring JDBC simplifies database interactions and makes CRUD (Create, Read, Update, Delete)
operations easy through the JdbcTemplate class. For deleting records, we use SQL DELETE
commands, which remove records from a database table based on specified conditions. Here’s how
you could create a program in Java to delete a record using Spring JDBC.
java
This method deletes an employee record based on id. The jdbcTemplate.update() method
executes the DELETE statement.
DML, or Data Manipulation Language, includes SQL commands that allow for inserting,
updating, and deleting data in database tables. Unlike DDL (Data Definition Language),
which changes the structure of the database (e.g., creating or modifying tables), DML
operates on the data stored within the tables. DML commands include INSERT, UPDATE,
DELETE, and SELECT.
sql
INSERT INTO Employee (id, name, department) VALUES (1, 'Alice',
'Marketing');
This command adds a new employee record with id 1, name "Alice," and department
"Marketing" to the Employee table.
sql
Here, the command changes the department of the employee with id 1 to "HR".
sql
This command deletes the record of the employee whose id is 1 from the Employee
table.
4. SELECT: Retrieves data from a table (not strictly a "modification" but falls under
DML as it manipulates data for retrieval).
o Example: Retrieving all employees in the Employee table.
sql
This command selects and displays all records in the Employee table.
DML (Data Manipulation Language) operations allow us to manage data within database
tables. Using Spring JDBC, we can easily perform operations like inserting, updating, or
deleting records through the JdbcTemplate class.
Below is an example program to insert a new employee record using Spring JDBC. This
demonstrates how to set up a Spring JDBC environment and use JdbcTemplate for executing
SQL DML commands.
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
if (rowsAffected > 0) {
System.out.println("Employee inserted successfully!");
} else {
System.out.println("Failed to insert employee.");
}
}
}
Explanation:
1. SQL Query: The SQL INSERT INTO command inserts values into the Employee table.
2. Executing the Query: The jdbcTemplate.update(sql, id, name, department)
method executes the query, with parameters id, name, and department.
3. Result: If the insertion succeeds (rowsAffected > 0), a success message is displayed.
Spring JDBC’s JdbcTemplate is very useful for such DML operations, providing a
straightforward way to interact with relational databases.
Reading records from a database is one of the essential operations when managing data.
Using Spring JDBC, we can retrieve and display records with ease. Here’s an example to
fetch and display employee records from an Employee table.
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department=" +
department + "]";
}
}
Explanation:
1. SQL Query: The SQL SELECT * FROM Employee command retrieves all records from the
Employee table.
2. RowMapper: The RowMapper interface maps each row in the ResultSet to a new
Employee object.
3. Result: The getAllEmployees method returns a list of Employee objects, each
representing a record from the table.
When called, this method returns a list of all employees, which can then be printed or
processed further. This setup leverages Spring JDBC’s query handling, making data retrieval
straightforward.
These examples demonstrate how Spring JDBC’s JdbcTemplate provides an efficient and
clean way to handle DML operations, from inserting records to reading and displaying them,
enhancing the ease and effectiveness of database interaction in Java applications.