0% found this document useful (0 votes)
9 views

Preparatory Notes_ FSW

The document provides an overview of Java Networking and Remote Method Invocation (RMI), detailing key components like sockets, URL handling, and RMI architecture. It covers socket programming, URL and URLConnection classes, and the steps to implement RMI applications. Additionally, it introduces JavaFX for building modern GUI applications, explaining its architecture and features such as 2D shapes and transformations.

Uploaded by

ayush.paradox75
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Preparatory Notes_ FSW

The document provides an overview of Java Networking and Remote Method Invocation (RMI), detailing key components like sockets, URL handling, and RMI architecture. It covers socket programming, URL and URLConnection classes, and the steps to implement RMI applications. Additionally, it introduces JavaFX for building modern GUI applications, explaining its architecture and features such as 2D shapes and transformations.

Uploaded by

ayush.paradox75
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Preparatory Notes: Java Networking & RMI

1. Java Networking

Java networking enables communication between devices and applications over a network. It
allows the exchange of data using standard protocols. Here’s a breakdown of the key
components and classes involved in Java Networking:

1.1 Introduction to Networking Concepts

Networking is the communication between computers, devices, or applications over a network.


Key concepts include:

● IP Address: A unique identifier for a device on a network (e.g., IPv4, IPv6).


● Port: A communication endpoint that identifies specific processes/services on a device.
● Protocols: Rules governing data transmission, e.g., TCP/IP, HTTP, FTP.

Java supports networking through APIs in the java.net package.

1.2 Socket Programming

Sockets are endpoints for communication between two machines. Java provides the Socket
and ServerSocket classes for implementing client-server communication.

Key Classes:

Socket: Used for creating a client-side connection.


java
Copy code
Socket socket = new Socket("127.0.0.1", 5000); // Connects to a server
at localhost on port 5000

ServerSocket: Used to create a server that listens for incoming connections.


java
Copy code
ServerSocket server = new ServerSocket(5000);
Socket client = server.accept(); // Waits for a client to connect

Steps to Implement Socket Programming:

1. Server-Side:
○ Create a ServerSocket object.
○ Wait for a connection using accept().
○ Communicate with the client via input/output streams.
2. Client-Side:
○ Create a Socket object to connect to the server.
○ Use input/output streams for communication.

Example: Server Code:

java
Copy code
import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is listening...");
Socket socket = serverSocket.accept();

InputStream input = socket.getInputStream();


BufferedReader reader = new BufferedReader(new
InputStreamReader(input));
String message = reader.readLine();
System.out.println("Client says: " + message);

socket.close();
serverSocket.close();
}
}

Client Code:

java
Copy code
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 5000);

OutputStream output = socket.getOutputStream();


PrintWriter writer = new PrintWriter(output, true);
writer.println("Hello, Server!");

socket.close();
}
}

1.3 URL Class

The URL class in Java represents a Uniform Resource Locator, which is used to locate
resources on the internet.

Usage:

java
Copy code
import java.net.*;

public class URLExample {


public static void main(String[] args) throws
MalformedURLException {
URL url = new
URL("https://www.example.com:80/index.html?query=java#section");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("File: " + url.getFile());
System.out.println("Reference: " + url.getRef());
}
}
Output:

● Protocol: https
● Host: www.example.com
● Port: 80
● File: /index.html?query=java
● Reference: section

1.4 URLConnection Class

The URLConnection class represents a connection to a URL. It can be used to read/write data
to/from a URL.

Example:

java
Copy code
import java.io.*;
import java.net.*;

public class URLConnectionExample {


public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();

BufferedReader reader = new BufferedReader(new


InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}

1.5 HttpURLConnection

HttpURLConnection is a subclass of URLConnection that supports HTTP-specific features.


Example:

java
Copy code
import java.io.*;
import java.net.*;

public class HttpURLConnectionExample {


public static void main(String[] args) throws IOException {
URL url = new
URL("https://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();


System.out.println("Response Code: " + responseCode);

BufferedReader reader = new BufferedReader(new


InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}

1.6 InetAddress Class

The InetAddress class represents an IP address.

Methods:

● getLocalHost(): Gets the local host IP.


● getByName(String host): Gets the IP address of a host.

Example:

java
Copy code
import java.net.*;

public class InetAddressExample {


public static void main(String[] args) throws UnknownHostException
{
InetAddress local = InetAddress.getLocalHost();
System.out.println("Local Host: " + local.getHostName());
System.out.println("Local IP: " + local.getHostAddress());

InetAddress remote = InetAddress.getByName("www.google.com");


System.out.println("Remote Host: " + remote.getHostName());
System.out.println("Remote IP: " + remote.getHostAddress());
}
}

1.7 DatagramSocket Class

This class is used for sending and receiving data packets using the UDP protocol. UDP is faster
but less reliable compared to TCP.

Example: Server:

java
Copy code
import java.net.*;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData()).trim();
System.out.println("Received: " + message);

serverSocket.close();
}
}

Client:

java
Copy code
import java.net.*;

public class UDPClient {


public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = "Hello, Server!".getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData,


sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);

clientSocket.close();
}
}

2. Remote Method Invocation (RMI)

RMI is a mechanism in Java that allows objects to communicate and invoke methods remotely.
This is especially useful for distributed applications.

2.1 Key Components:

1. Stub and Skeleton:


○ Stub acts as a client-side proxy for the remote object.
○ Skeleton (used in older versions) acts as a server-side helper.
2. RMI Registry: A naming service that allows clients to look up remote objects.

2.2 Steps for RMI Implementation:

1. Define a remote interface.


2. Implement the interface.
3. Compile with rmic to generate stubs.
4. Create the server and client programs.
5. Start the RMI registry.

2. RMI (Remote Method Invocation)

RMI enables Java objects to communicate and invoke methods on remote objects over a
network, allowing distributed applications to run seamlessly. It abstracts the complexity of
communication between JVMs.

2.1 Key Components of RMI

1. Remote Interface:
○ Defines the methods that can be invoked remotely.
○ It extends java.rmi.Remote.
○ All methods must declare throws RemoteException.
2. Remote Object:
○ Implements the remote interface.
○ Defines the behavior for the methods.
3. Stub and Skeleton:
○ Stub: Client-side proxy for the remote object that forwards the method calls to
the server.
○ Skeleton: Server-side helper (used in Java versions prior to 1.5) that dispatches
the request to the actual remote object.
4. RMI Registry:
○ A naming service that allows clients to look up remote objects.
5. RMI Server and Client:
○ Server: Registers the remote object with the RMI registry.
○ Client: Looks up the object in the RMI registry and invokes methods.

2.2 Steps to Implement RMI

Here’s how to build a simple RMI application step by step:

Step 1: Define the Remote Interface

The remote interface declares the methods that can be invoked remotely.
Example:

java
Copy code
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote {


int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
}

Step 2: Implement the Remote Object

The remote object implements the remote interface.

Example:

java
Copy code
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class CalculatorImpl extends UnicastRemoteObject implements


Calculator {
protected CalculatorImpl() throws RemoteException {
super();
}

@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}

@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}
}
Step 3: Create the RMI Server

The server program creates an instance of the remote object and registers it with the RMI
registry.

Example:

java
Copy code
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RMIServer {


public static void main(String[] args) {
try {
Calculator calculator = new CalculatorImpl();
Registry registry = LocateRegistry.createRegistry(1099);
// Default port 1099
registry.rebind("CalculatorService", calculator);
System.out.println("RMI Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 4: Create the RMI Client

The client program looks up the remote object and invokes methods on it.

Example:

java
Copy code
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RMIClient {


public static void main(String[] args) {
try {
Registry registry =
LocateRegistry.getRegistry("localhost", 1099);
Calculator calculator = (Calculator)
registry.lookup("CalculatorService");

System.out.println("Addition: " + calculator.add(10, 5));


System.out.println("Subtraction: " +
calculator.subtract(10, 5));
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 5: Compile and Run


Compile all Java files:
bash
Copy code
javac *.java

1.

Generate the stub file (only needed for Java versions < 1.5):
bash
Copy code
rmic CalculatorImpl

2.

Start the RMI Registry:


bash
Copy code
rmiregistry

3.

Run the server:


bash
Copy code
java RMIServer

4.

Run the client:


bash
Copy code
java RMIClient

5.

2.3 Advantages of RMI

● Object-Oriented: Allows remote method invocation directly on objects.


● Transparent: Simplifies networking code by abstracting underlying protocols.
● Java to Java Communication: Tailored for Java-based distributed systems.

2.4 Implementation with Database

RMI can be extended to access a database. For example, you can create a remote interface for
querying data from a database.

Example Remote Interface:

java
Copy code
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface DatabaseService extends Remote {


List<String> getData() throws RemoteException;
}

Example Implementation:

java
Copy code
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseServiceImpl extends UnicastRemoteObject


implements DatabaseService {
protected DatabaseServiceImpl() throws RemoteException {
super();
}

@Override
public List<String> getData() throws RemoteException {
List<String> data = new ArrayList<>();
data.add("Record 1");
data.add("Record 2");
return data;
}
}

Summary

RMI is a powerful feature of Java for developing distributed systems, allowing remote method
calls between JVMs. With RMI, you can easily build applications that communicate over a
network while keeping the complexity of underlying protocols hidden.

3. JavaFX

JavaFX is a powerful framework for building rich, modern, and visually appealing desktop
applications. It provides a wide range of tools and libraries for GUI (Graphical User Interface)
development.

3.1 Introduction

JavaFX is the successor to Swing, providing a more modern and flexible platform for GUI
development. It uses:
● FXML: An XML-based markup language to design UI.
● CSS: To style applications, similar to web development.
● Scene Graph: A hierarchical tree of nodes (UI components) for building the GUI.

3.2 JavaFX Architecture

JavaFX is based on a layered architecture consisting of the following components:

1. Stage:
○ Represents the top-level container (window).
○ Created by the JavaFX runtime when the application starts.
2. Scene:
○ Represents the content inside the stage.
○ Contains a tree of nodes (Scene Graph).
3. Nodes:
○ The building blocks of JavaFX applications (e.g., buttons, text fields, shapes).
4. Event Handling:
○ Mechanism to respond to user actions like button clicks or mouse events.

3.3 Building a JavaFX Application

A JavaFX application follows these steps:

1. Extend the Application Class.


2. Override the start() Method.
3. Create a Stage and Scene.
4. Add Nodes to the Scene.
5. Launch the Application.

Example: A simple JavaFX application

java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXExample extends Application {


@Override
public void start(Stage primaryStage) {
Button button = new Button("Click Me!");
button.setOnAction(e -> System.out.println("Button
clicked!"));

StackPane root = new StackPane();


root.getChildren().add(button);

Scene scene = new Scene(root, 300, 200);


primaryStage.setTitle("JavaFX Example");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

3.4 2D Shapes

JavaFX provides a variety of 2D shapes for drawing graphics:

1. Line: Draws a straight line.


2. Rectangle: Draws a rectangle or square.
3. Circle: Draws a circle.
4. Ellipse: Draws an ellipse.
5. Polygon: Draws a closed shape with multiple vertices.

Example: Drawing shapes

java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ShapesExample extends Application {


@Override
public void start(Stage stage) {
Circle circle = new Circle(100, 100, 50, Color.BLUE);
Rectangle rectangle = new Rectangle(200, 200, 100, 50);
rectangle.setFill(Color.RED);

Pane pane = new Pane();


pane.getChildren().addAll(circle, rectangle);

Scene scene = new Scene(pane, 400, 300);


stage.setTitle("JavaFX Shapes Example");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

3.5 Transformations

JavaFX provides transformations to manipulate shapes and nodes. Common transformations


include:

● Translate: Moves a node to a new position.


● Rotate: Rotates a node.
● Scale: Resizes a node.
● Shear: Skews a node.

Example:

java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class TransformationExample extends Application {


@Override
public void start(Stage stage) {
Rectangle rectangle = new Rectangle(50, 50, 100, 50);
rectangle.setFill(Color.GREEN);

// Apply transformations
rectangle.setRotate(45); // Rotates by 45 degrees

Pane pane = new Pane();


pane.getChildren().add(rectangle);

Scene scene = new Scene(pane, 400, 300);


stage.setTitle("Transformations in JavaFX");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

3.6 Animation

JavaFX provides built-in support for animations to create dynamic and visually appealing
interfaces. Examples include:

● FadeTransition: Changes a node’s opacity over time.


● TranslateTransition: Moves a node from one position to another.
● RotateTransition: Rotates a node.
● ScaleTransition: Changes a node’s size.
Example:

java
Copy code
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimationExample extends Application {


@Override
public void start(Stage stage) {
Circle circle = new Circle(100, Color.BLUE);

// Create a fade transition


FadeTransition fade = new FadeTransition(Duration.seconds(2),
circle);
fade.setFromValue(1.0); // Start fully visible
fade.setToValue(0.3); // Fade to 30% opacity
fade.setCycleCount(4); // Repeat 4 times
fade.setAutoReverse(true);

fade.play(); // Start the animation

StackPane pane = new StackPane(circle);


Scene scene = new Scene(pane, 400, 300);
stage.setTitle("JavaFX Animation Example");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}
3.7 Media with JavaFX

JavaFX supports multimedia (audio and video) playback using the Media and MediaPlayer
classes.

Example:

java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

public class MediaExample extends Application {


@Override
public void start(Stage stage) {
String mediaPath = "file:///path/to/media/file.mp4"; //
Replace with the actual file path
Media media = new Media(mediaPath);
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);

Scene scene = new Scene(mediaView, 800, 600);


stage.setTitle("JavaFX Media Example");
stage.setScene(scene);
stage.show();

mediaPlayer.play(); // Start playback


}

public static void main(String[] args) {


launch(args);
}
}
3.8 Event Handling

Event handling in JavaFX is based on the Event-Driven Programming model. Commonly used
event classes:

● MouseEvent: Handles mouse actions like clicks and drags.


● KeyEvent: Handles keyboard input.
● ActionEvent: Handles actions like button clicks.

Example:

java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class EventHandlingExample extends Application {


@Override
public void start(Stage stage) {
Button button = new Button("Click Me!");
button.setOnAction(e -> System.out.println("Button
clicked!"));

StackPane pane = new StackPane(button);


Scene scene = new Scene(pane, 300, 200);
stage.setTitle("Event Handling in JavaFX");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}
Summary

JavaFX is a comprehensive framework for building GUI-based desktop applications. It provides


advanced tools for designing, styling, and animating UIs, making it a powerful successor to
Swing.

4. Java Struts

Java Struts is a popular open-source framework used for building Java-based web applications.
It follows the MVC (Model-View-Controller) architecture, which separates the application logic
into three interconnected components, making it easier to maintain and scale.

4.1 Introduction to Struts

Struts is built on top of Servlets and JSP (JavaServer Pages) and provides a robust framework
to manage user input, process business logic, and display the output in a structured way.

4.2 Features of Struts

1. MVC Architecture:
○ Separates application into:
■ Model: Represents the application's data and business logic.
■ View: Handles presentation (e.g., JSP pages).
■ Controller: Manages user requests and responses (e.g., Action classes).
2. Action Classes:
○ Encapsulates business logic.
○ Processes user requests.
3. Tag Libraries:
○ Simplify JSP coding with pre-defined tags for HTML forms, data display, etc.
4. Validation Framework:
○ Provides built-in support for validating user inputs.
5. Extensibility:
○ Developers can extend Struts' classes and functionality as needed.
6. Integration:
○ Easily integrates with other frameworks like Hibernate and Spring.

4.3 Architecture of Struts


The architecture of Struts involves the following major components:

1. Controller (ActionServlet):
○ A core component of Struts that handles incoming requests.
○ Maps requests to appropriate Action classes.
2. Action Classes:
○ Represent business logic.
○ Use helper classes to interact with the model layer.
3. Model:
○ Represents the application's data.
○ Can integrate with databases or external APIs.
4. View:
○ The user interface built using JSP or other presentation technologies.

Workflow of Struts:

1. A user sends a request to the Struts controller (ActionServlet).


2. The controller consults the struts-config.xml file to determine which Action class to
invoke.
3. The Action class processes the request and updates the model.
4. The result is passed back to the controller.
5. The controller selects the appropriate view (e.g., JSP) to render the response.

4.4 Key Components in Detail

1. ActionServlet:
○ Main controller that routes HTTP requests to appropriate Action classes.
○ Defined in the web.xml file.

Example (web.xml):
xml
Copy code
<servlet>
<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2.
3. struts-config.xml:
○ Central configuration file for Struts.
○ Maps user requests to Action classes and specifies forward navigation.

Example (struts-config.xml):
xml
Copy code
<action-mappings>
<action path="/login"
type="com.example.LoginAction"
name="loginForm"
scope="request"
validate="true">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>
</action-mappings>

4.
5. ActionForm:
○ Represents the form data submitted by the user.
○ Populates Action classes with the submitted data.

Example:
java
Copy code
public class LoginForm extends ActionForm {
private String username;
private String password;

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; }
}

6.
7. Action Classes:
○ Handle user requests and business logic.

Example:
java
Copy code
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm
form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if ("admin".equals(loginForm.getUsername()) &&
"password".equals(loginForm.getPassword())) {
return mapping.findForward("success");
} else {
return mapping.findForward("failure");
}
}
}

8.
9. Tag Libraries:
○ Provides reusable components for JSP.
○ Common tags:
■ <html:form>: Creates a form.
■ <html:text>: Creates a text field.
■ <html:submit>: Creates a submit button.

Example JSP:
jsp
Copy code
<html:form action="/login">
Username: <html:text property="username" /><br>
Password: <html:password property="password" /><br>
<html:submit value="Login" />
</html:form>

10.
4.5 Interceptors

Interceptors are used to process requests and responses in Struts.

1. Custom Interceptor:
○ Used to execute logic before or after the Action class executes.

Example Custom Interceptor:


java
Copy code
public class LoggingInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocation) throws
Exception {
System.out.println("Before action execution");
invocation.invoke();
System.out.println("After action execution");
}
}

2.
3. Built-in Interceptors:
○ File Upload: Handles file uploads.
○ Exception Handling: Captures exceptions and processes them.

4.6 Validation in Struts

Struts provides a built-in validation framework for form data. You can define validation rules in
an XML file or directly in the ActionForm class.

Example Validation XML:

xml
Copy code
<form-beans>
<form-bean name="loginForm" type="com.example.LoginForm" />
</form-beans>

<form-validation>
<formset>
<form name="loginForm">
<field property="username" depends="required">
<arg0 key="error.username.required" />
</field>
<field property="password" depends="required">
<arg0 key="error.password.required" />
</field>
</form>
</formset>
</form-validation>

4.7 Advantages of Struts

1. Simplifies Development: Manages MVC architecture efficiently.


2. Reusability: Tag libraries and Action classes promote reusability.
3. Integration: Works well with other frameworks and libraries like Hibernate.
4. Validation Framework: Reduces boilerplate code for validation.

Summary

Struts is a robust framework for building scalable and maintainable web applications using Java.
Its MVC architecture, validation framework, and integration capabilities make it ideal for
enterprise-level projects.

5. Bundled Validation

Bundled validation refers to predefined, reusable validation mechanisms provided by


frameworks or libraries. These validations are used to ensure that user input adheres to certain
rules or formats, reducing errors and improving data consistency.

In frameworks like Java Struts, bundled validation provides out-of-the-box validators that can
be easily integrated into your application.

5.1 Introduction
Validation ensures that user input matches the expected format or criteria before processing it.
Bundled validation saves time by offering pre-implemented validators for common input types
like:

● Strings
● Numbers
● Dates
● Emails
● URLs
● Regular expressions (Regex)

5.2 Common Bundled Validators

1. StringLength Validator:
○ Ensures that a string has a minimum and/or maximum length.
○ Commonly used for validating names, usernames, etc.

Example Configuration:
xml
Copy code
<field property="username" depends="required,stringlength">
<arg0 key="error.username.length" />
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>15</var-value>
</var>
</field>

2.
3. Email Validator:
○ Ensures that input is a valid email address format.

Example Configuration:
xml
Copy code
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>

4.
5. Date Validator:
○ Ensures that the input is a valid date and optionally within a certain range.

Example Configuration:
xml
Copy code
<field property="birthDate" depends="required,date">
<arg0 key="error.birthDate.invalid" />
</field>

6.
7. URL Validator:
○ Ensures that the input is a valid URL format.

Example Configuration:
xml
Copy code
<field property="website" depends="url">
<arg0 key="error.website.invalid" />
</field>

8.
9. Regex Validator:
○ Validates input against a regular expression.

Example Configuration:
xml
Copy code
<field property="zipcode" depends="mask">
<arg0 key="error.zipcode.invalid" />
<var>
<var-name>mask</var-name>
<var-value>^[0-9]{5}(?:-[0-9]{4})?$</var-value>
</var>
</field>

10.
11. Int/Double Validator:
○ Ensures that the input is a valid integer or decimal number.
Example Configuration:
xml
Copy code
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>

12.

5.3 Custom Validation

While bundled validators handle common cases, some applications may require custom
validation logic. Struts allows developers to create their own validators.

Steps to Create Custom Validators:

1. Extend the ValidatorForm class or implement the ActionForm class.


2. Override the validate method to add custom validation logic.

Example Custom Validator:

java
Copy code
public class CustomValidationForm extends ValidatorForm {
private String username;

public String getUsername() { return username; }


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

@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();

if (username == null || username.length() < 5) {


errors.add("username", new
ActionMessage("error.username.length"));
}
return errors;
}
}

5.4 Validation Framework Configuration

1. Validation.xml:
○ Central file for defining validation rules for ActionForms.
○ Includes bundled validators and their configurations.

Example:
xml
Copy code
<form-validation>
<formset>
<form name="userForm">
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>
</form>
</formset>
</form-validation>

2.
3. Application Resource File:
○ Contains error messages associated with validation.

Example:
properties
Copy code
error.username.length=Username must be between 5 and 15 characters.
error.email.invalid=Please enter a valid email address.
error.age.invalid=Age must be a valid number.

4.

5.5 Advantages of Bundled Validation


1. Ease of Use: Predefined validators reduce development time.
2. Consistency: Ensures uniform validation rules across the application.
3. Flexibility: Custom validators can handle complex validation scenarios.
4. Error Localization: Supports internationalization with localized error messages.

5.6 Practical Example

Scenario: A login form requires:

● Username (5-15 characters).


● Email (valid format).
● Age (integer).

struts-config.xml:

xml
Copy code
<action-mappings>
<action path="/login"
type="com.example.LoginAction"
name="loginForm"
scope="request"
validate="true">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>
</action-mappings>

Validation.xml:

xml
Copy code
<form-validation>
<formset>
<form name="loginForm">
<field property="username"
depends="required,stringlength">
<arg0 key="error.username.length" />
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>15</var-value>
</var>
</field>
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>
</form>
</formset>
</form-validation>

Application Resources File:

properties
Copy code
error.username.length=Username must be between 5 and 15 characters.
error.email.invalid=Invalid email format.
error.age.invalid=Age must be a number.

Summary

Bundled validation in frameworks like Struts simplifies input validation by providing reusable and
standardized validators. These validators help maintain consistent and error-free user input
while allowing customization for unique requirements.

6. AngularJS

AngularJS is a powerful JavaScript-based open-source framework used for building dynamic


web applications. Developed by Google, it simplifies the development of Single Page
Applications (SPAs) by providing features like two-way data binding, dependency injection, and
modularization.
6.1 Introduction

AngularJS extends HTML by adding custom tags and attributes, enabling the creation of
interactive and dynamic web interfaces. It integrates seamlessly with RESTful APIs and
promotes a clean MVC architecture for structuring applications.

Key Features of AngularJS:

1. Two-Way Data Binding: Automatically synchronizes data between the model and the
view.
2. Dependency Injection (DI): Provides a mechanism to inject dependencies into
components, making the application more modular and testable.
3. Directives: Custom HTML attributes that define behavior or structure in the DOM.
4. Filters: Transform data for display in views.
5. Routing: Facilitates SPA development by loading views dynamically based on URL
changes.

6.2 AngularJS MVC Architecture

AngularJS follows a slightly modified MVC pattern:

● Model: Manages application data.


● View: Defines the user interface using HTML and Angular expressions.
● Controller: Processes user input and updates the model or view as necessary.

6.3 AngularJS Components

1. Modules:
○ Containers for different parts of an application (e.g., controllers, services, filters).
○ Defined using angular.module.

Example:
javascript
Copy code
var app = angular.module('myApp', []);

2.
3. Controllers:
○ JavaScript functions that define the business logic for a specific view.
○ Attached to HTML elements using the ng-controller directive.
Example:
javascript
Copy code
app.controller('myCtrl', function($scope) {
$scope.greeting = "Hello, AngularJS!";
});
HTML:
html
Copy code
<div ng-controller="myCtrl">
{{greeting}}
</div>

4.
5. Directives:
○ Special markers in the DOM that AngularJS uses to attach behavior.
○ Examples:
■ ng-model: Binds input values to the model.
■ ng-repeat: Repeats elements for each item in a collection.
■ ng-click: Binds click events to functions.

Example:
html
Copy code
<input ng-model="name">
<p>Hello, {{name}}</p>

6.
7. Filters:
○ Used to format data displayed in the view.
○ Examples:
■ currency: Formats numbers as currency.
■ uppercase: Converts text to uppercase.
■ date: Formats dates.

Example:
html
Copy code
<p>{{price | currency}}</p>

8.
9. Services:
○ Singleton objects responsible for managing data and reusable functionality.
○ Examples:
■ $http: For making HTTP requests.
■ $timeout: For delays.
■ $routeParams: For routing.

Example Service:
javascript
Copy code
app.service('myService', function() {
this.sayHello = function(name) {
return "Hello, " + name + "!";
};
});

10.

6.4 Two-Way Data Binding

Two-way data binding ensures that changes in the model reflect automatically in the view and
vice versa.

Example:

html
Copy code
<div ng-controller="myCtrl">
<input ng-model="message">
<p>You typed: {{message}}</p>
</div>

Here, the value typed into the input field updates message in the model, and the paragraph
content reflects these changes in real-time.

6.5 AngularJS Directives

Directives are the building blocks of AngularJS and can be used to create dynamic, reusable
components.

1. Built-In Directives:
○ ng-app: Initializes an AngularJS application.
○ ng-bind: Binds expressions to HTML elements.
○ ng-init: Initializes variables in the scope.
2. Custom Directives:
○ Developers can create their own directives to encapsulate reusable components.

Example:
javascript
Copy code
app.directive('myDirective', function() {
return {
template: "<h1>Custom Directive!</h1>"
};
});
Usage in HTML:
html
Copy code
<div my-directive></div>

3.

6.6 Forms and Validation

AngularJS simplifies form creation and validation using directives and built-in validators.

Form Validation Example:

html
Copy code
<form name="myForm">
<input type="text" name="username" ng-model="username" required>
<span ng-show="myForm.username.$error.required">Username is
required.</span>
</form>

Here:

● ng-model: Binds the input value to the model.


● $error: Tracks validation errors.
6.7 Routing in AngularJS

Routing allows developers to build SPAs by dynamically loading views based on the URL.

1. Setting Up Routing:
○ Add the ngRoute module.
○ Define routes using $routeProvider.

Example:
javascript
Copy code
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'homeCtrl'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'aboutCtrl'
});
});

2.

HTML Example:
html
Copy code
<a href="#!/home">Home</a>
<a href="#!/about">About</a>
<div ng-view></div>

3.

6.8 AngularJS with AJAX

AngularJS simplifies AJAX requests using the $http service.

Example:

javascript
Copy code
app.controller('myCtrl', function($scope, $http) {
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
});
});

HTML:

html
Copy code
<ul>
<li ng-repeat="item in data">{{item.name}}</li>
</ul>

6.9 CRUD Operations

AngularJS can handle CRUD (Create, Read, Update, Delete) operations efficiently.

Example:

javascript
Copy code
app.controller('crudCtrl', function($scope) {
$scope.items = [];
$scope.addItem = function(item) {
$scope.items.push(item);
$scope.newItem = "";
};
$scope.removeItem = function(index) {
$scope.items.splice(index, 1);
};
});

HTML:

html
Copy code
<div ng-controller="crudCtrl">
<input ng-model="newItem">
<button ng-click="addItem(newItem)">Add</button>
<ul>
<li ng-repeat="item in items">
{{item}} <button
ng-click="removeItem($index)">Remove</button>
</li>
</ul>
</div>

6.10 Advantages of AngularJS

1. Simplifies Development: Features like two-way binding and directives reduce coding
effort.
2. Reusable Components: Directives and services promote code reuse.
3. Dynamic UI: Enables the creation of interactive and responsive interfaces.
4. Testability: Dependency injection and modularity simplify testing.

Summary

AngularJS provides a comprehensive framework for building dynamic, modular, and


maintainable web applications. Its rich set of features like data binding, routing, and validation
make it ideal for developing SPAs.

7. MongoDB

MongoDB is a NoSQL database that provides high performance, high availability, and
scalability. Unlike traditional relational databases, MongoDB stores data in a flexible, JSON-like
document format, allowing developers to work with unstructured or semi-structured data
seamlessly.

7.1 Introduction to MongoDB

MongoDB is designed to handle large volumes of data with features like:

● Document-Oriented Storage: Data is stored in BSON (Binary JSON) documents.


● Schema Flexibility: No predefined schema; fields can vary across documents.
● Scalability: Supports horizontal scaling using sharding.
● Indexing: Provides efficient querying with a variety of indexes.

Use Cases:

● Real-time analytics
● Content management systems
● Internet of Things (IoT) applications
● E-commerce platforms

7.2 Advantages over RDBMS

1. Schema-less Design:
○ No rigid table structure; documents in a collection can have different fields.
2. Scalability:
○ Supports sharding, which splits data across multiple servers for load balancing.
3. Faster Queries:
○ Optimized for unstructured data, making queries faster in some use cases.
4. Flexibility:
○ Handles complex hierarchical data directly in a single document.
5. Ease of Use:
○ No need for complex JOIN operations.

Comparison with RDBMS:

Feature MongoDB RDBMS

Data Model Document-Oriented Table-Oriented

Schema Flexible (Schema-less) Fixed Schema

Scalability Horizontal (Sharding) Vertical

Query JSON-based (MongoDB Query) SQL


Language

7.3 MongoDB Data Types

MongoDB supports the following data types:

● String: Used for storing text.


● Number: Includes integers and floating-point numbers.
● Boolean: Represents true or false values.
● Date: Stores date and time.
● Array: Stores multiple values in a single field.
● Object: Stores nested documents.
● Binary Data: For storing files like images.
● ObjectId: A unique identifier for each document.

7.4 Installing MongoDB

1. Download MongoDB:
○ Visit MongoDB Downloads and choose the appropriate version for your OS.
2. Installation:
○ Follow the instructions for your operating system (Windows, Linux, macOS).
3. Run MongoDB Server:
○ Use the command mongod to start the MongoDB server.
4. Connect to MongoDB:
○ Use the command-line tool mongo or a GUI client like MongoDB Compass.

7.5 Data Modelling in MongoDB

MongoDB uses collections instead of tables, and documents instead of rows.

1. Document Structure:
○ Documents are JSON-like objects with key-value pairs.

Example Document:
json
Copy code
{
"_id": "12345",
"name": "Alice",
"email": "[email protected]",
"orders": [
{ "order_id": "1", "item": "Laptop", "price": 1200 },
{ "order_id": "2", "item": "Phone", "price": 800 }
]
}


2. Collections:
○ Collections group related documents.
○ Unlike tables, collections do not enforce a schema.
3. Data Relationships:
○ Embedded Documents: Data is nested within a single document.
○ References: Documents reference other documents by their IDs.

7.6 MongoDB CRUD Operations

1. Create (Insert):
○ Adds new documents to a collection.

Example:
javascript
Copy code
db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
]);

2.
3. Read (Find):
○ Retrieves documents from a collection.

Example:
javascript
Copy code
db.users.find(); // Fetch all documents
db.users.find({ age: { $gt: 25 } }); // Fetch users older than 25

4.
5. Update:
○ Modifies existing documents.

Example:
javascript
Copy code
db.users.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 31 } } // Update
);
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
);

6.
7. Delete:
○ Removes documents from a collection.

Example:
javascript
Copy code
db.users.deleteOne({ name: "Charlie" });
db.users.deleteMany({ age: { $gt: 50 } });

8.

7.7 MongoDB Operators

1. Comparison Operators:
○ $gt (greater than), $lt (less than), $gte (greater than or equal), $lte (less
than or equal), $eq (equal), $ne (not equal).

Example:
javascript
Copy code
db.users.find({ age: { $gte: 30 } });

2.
3. Logical Operators:
○ $and, $or, $not, $nor.

Example:
javascript
Copy code
db.users.find({ $or: [{ age: { $lt: 25 } }, { name: "Alice" }] });

4.
5. Array Operators:
○ $in, $nin, $all, $size.

Example:
javascript
Copy code
db.orders.find({ items: { $all: ["laptop", "mouse"] } });
6.
7. Update Operators:
○ $set, $unset, $inc, $push, $pull.

Example:
javascript
Copy code
db.users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });

8.

7.8 MongoDB Connectivity

1. Node.js Integration:
○ MongoDB integrates with Node.js using the mongodb or mongoose library.

Example using Mongoose:


javascript
Copy code
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser:
true });

const userSchema = new mongoose.Schema({


name: String,
age: Number
});

const User = mongoose.model('User', userSchema);

User.create({ name: "Alice", age: 30 }, (err, user) => {


if (err) console.error(err);
console.log(user);
});

2.
3. Using MongoDB Compass:
○ GUI tool for managing MongoDB databases visually.
7.9 Summary of Key Commands
Operation Command Example

Insert db.collection.insertOne({...})

Find db.collection.find({ key: value })

Update db.collection.updateOne({ filter }, {


$set: {...} })

Delete db.collection.deleteOne({ filter })

Create db.collection.createIndex({ key: 1 })


Index

Summary

MongoDB's flexibility, scalability, and document-oriented approach make it ideal for modern web
applications handling large and diverse datasets. Its seamless integration with tools like Node.js
further enhances its utility for developers.

You might also like