0% found this document useful (0 votes)
23 views26 pages

Understanding MVC Architecture Basics

The document explains the Model-View-Controller (MVC) architecture, detailing its components: Model for data management, View for data presentation, and Controller for handling user interactions. It highlights the advantages of MVC, such as separation of concerns and scalability, as well as its disadvantages, including increased complexity. Additionally, it introduces the Struts framework, which is based on MVC, and outlines its architecture, workflow, and steps to build a Struts application.
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)
23 views26 pages

Understanding MVC Architecture Basics

The document explains the Model-View-Controller (MVC) architecture, detailing its components: Model for data management, View for data presentation, and Controller for handling user interactions. It highlights the advantages of MVC, such as separation of concerns and scalability, as well as its disadvantages, including increased complexity. Additionally, it introduces the Struts framework, which is based on MVC, and outlines its architecture, workflow, and steps to build a Struts application.
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

Basic MVC Architecture

Model View Controller or MVC as it is popularly called, is a so ware design pa ern for developing
web applica ons. A Model View Controller pa ern is made up of the following three parts −

 Model − The lowest level of the pa ern which is responsible for maintaining data.

 View − This is responsible for displaying all or a por on of the data to the user.

 Controller − So ware Code that controls the interac ons between the Model and View.

MVC is popular as it isolates the applica on logic from the user interface layer and supports
separa on of concerns. Here the Controller receives all requests for the applica on and then works
with the Model to prepare any data needed by the View. The View then uses the data prepared by
the Controller to generate a final presentable response. The MVC abstrac on can be graphically
represented as follows.

The Model

The model is responsible for managing the data of the applica on. It responds to the request from
the view and it also responds to instruc ons from the controller to update itself.

The View

It means presenta on of data in a par cular format, triggered by a controller's decision to present
the data. They are script-based templa ng systems like JSP, ASP, PHP and very easy to integrate with
AJAX technology.

The Controller

The controller is responsible for responding to the user input and perform interac ons on the data
model objects. The controller receives the input, it validates the input and then performs the
business opera on that modifies the state of the data model.
Components of MVC Architecture

1. Model (Data Layer)

Represents the data and business logic of the applica on.

Fetches, stores, updates, and deletes data from a database or other data sources.

Independent of the user interface.

No fies the View when data changes (if using Observer pa ern).

Example in Java:

public class User {

private String name;

private int age;

public User(String name, int age) {

[Link] = name;

[Link] = age;

public String getName() { return name; }

public int getAge() { return age; }

2. View (Presenta on Layer)

Responsible for displaying data to the user.

Can be implemented using JSP, HTML, CSS, JavaScript, or frontend frameworks like React and
Angular.

Retrieves data from the Model but does not modify it.
Example in JSP:

<%@ page import="[Link]" %>

<%

User user = (User) [Link] ribute("user");

%>

<html>

<body>

<h2>User Details</h2>

<p>Name: <%= [Link]() %></p>

<p>Age: <%= [Link]() %></p>

</body>

</html>

3. Controller (Applica on Logic Layer)

Acts as an intermediary between Model and View.

Handles user input and updates the Model and View accordingly.

O en implemented using Java Servlets, Spring Controllers, or similar frameworks.

Example in Java Servlet:

@WebServlet("/user")

public class UserController extends H pServlet {

protected void doGet(H pServletRequest request, H pServletResponse response)

throws ServletExcep on, IOExcep on {

User user = new User("John Doe", 25);

[Link] ribute("user", user);

RequestDispatcher dispatcher = [Link]("[Link]");


[Link](request, response);

How MVC Works?

1. User Request: The user interacts with the View (e.g., clicks a bu on).

2. Controller Handles Request: The request is sent to the Controller.

3. Controller Interacts with Model: The Controller calls the Model to fetch or modify data.

4. Model Updates: The Model processes the request and updates the data.

5. View Displays Data: The updated data is sent back to the View for display.

Advantages of MVC Architecture

✔ Separa on of Concerns: Divides applica on logic into three separate layers, making code easier to
manage.

✔ Reusability: Components can be reused in different parts of the applica on.

✔ Scalability: Easy to extend and maintain applica ons.

✔ Mul ple Views: The same data (Model) can be represented in different ways (View) without
modifying the business logic.

Disadvantages of MVC Architecture

✖ Complexity: Increases the complexity of small applica ons.

✖ Learning Curve: Requires understanding of three separate components and their interac on.

✖ More Code: May require addi onal classes and files compared to tradi onal monolithic design.

Introduc on to Struts Framework


Struts is a Model-View-Controller (MVC) based Java framework used for building web applica ons. It
is an extension of Java Servlets and JSP, providing a structured way to develop scalable and
maintainable applica ons.
Struts simplifies request handling, form valida on, and page naviga on using a centralized
configura on system.

Struts Architecture

Struts follows the MVC (Model-View-Controller) pa ern and consists of the following key
components:

1. Model (Business Logic & Data Layer)


Represents the applica on's business logic and data.

Can interact with databases, services, and business logic classes.

Uses JavaBeans, Hibernate, or JDBC for data access.

Example Model ([Link])

public class User {

private String username;

private String password;

// Ge ers and Se ers

public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

2. View (Presenta on Layer - JSP & Struts Tags)

The user interface that displays data.

Uses JSP with Struts tags to display informa on dynamically.


Example View ([Link])

<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<body>

<h2>Welcome, <s:property value="username"/>!</h2>

</body>

</html>

3. Controller (Ac on Classes & Struts Configura on)

Processes user requests and interacts with the Model.

Uses Ac on classes instead of Servlets to handle requests.

Managed by Struts Ac onServlet (Controller).

Example Ac on Class (UserAc [Link])

import [Link] onSupport;

public class UserAc on extends Ac onSupport {

private String username;

private String password;

public String execute() {

if ("admin".equals(username) && "1234".equals(password)) {

return "success";

} else {

return "error";

}
}

// Ge ers and Se ers

public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

4. Configura on ([Link] & [Link])

Struts uses [Link] to map Ac ons to Views.

Example [Link] Configura on:

<struts>

<package name="default" extends="struts-default">

<ac on name="userLogin" class="[Link] [Link] on">

<result name="success">[Link]</result>

<result name="error">[Link]</result>

</ac on>

</package>

</struts>

Example [Link] Configura on:

<filter>

<filter-name>struts2</filter-name>

<filter-class>[Link]</filter-class>

</filter>
<filter-mapping>

<filter-name>struts2</filter-name>

<url-pa ern>/*</url-pa ern>

</filter-mapping>

Struts Tags (Struts UI Tags)

Struts provides custom JSP tags for easier form handling, itera on, and UI elements.

1. Form Tags

Used to create forms easily.

<s:form ac on="userLogin">

<s:tex ield name="username" label="Username"/>

<s:password name="password" label="Password"/>

<s:submit value="Login"/>

</s:form>

2. Property Tag

Displays data from Ac on class.

<p>Welcome, <s:property value="username"/>!</p>

3. If & Else Tags

Used for condi onal checks in JSP.

<s:if test="%{username == 'admin'}">


<p>Admin Access Granted</p>

</s:if>

<s:else>

<p>Access Denied</p>

</s:else>

4. Iterator Tag

Used to loop over lists.

<s:iterator value="userList">

<p><s:property value="username"/></p>

</s:iterator>

5. Include & URL Tags

<s:include value="[Link]"/>

<s:url ac on="userLogin" var="loginURL"/>

Struts Workflow (Request Processing Steps)

1. User Request: A user submits a form or accesses a URL.

2. Struts Controller: FilterDispatcher receives the request.

3. Ac on Execu on: The appropriate Ac on class processes the request.

4. Business Logic: The Model is accessed to process data.

5. Response to View: The response is sent to a JSP file.

6. View Renders Output: JSP displays the output to the user.

Advantages of Struts
✔ MVC-Based Architecture – Clean code separa on.

✔ Reusable Components – Struts tags simplify development.

✔ Centralized Configura on – [Link] for easy management.

✔ Supports Interceptors & Valida on – Built-in support for authen ca on and input valida on.

Disadvantages of Struts

✖ Complexity – Requires configura on and learning curve.

✖ Slower than Lightweight Frameworks – Spring MVC is o en preferred for modern development.

✖ Requires XML Configura on – Unlike newer frameworks that use annota ons.

Introduc on to Struts Control Flow

Struts follows the Model-View-Controller (MVC) architecture to handle web requests efficiently. The
control flow in Struts is managed by the FilterDispatcher (Struts 2) or Ac onServlet (Struts 1), which
acts as a central controller to process client requests, execute business logic, and return the
appropriate view response.

Struts Request Processing Flow

1. Client Request Ini a on

The user sends a request through a browser by clicking a link, submi ng a form, or accessing a URL.

The request is intercepted by Struts FilterDispatcher (Struts 2) or Ac onServlet (Struts 1).

2. Struts Controller Intercep on

The request passes through FilterDispatcher (Struts 2), which iden fies the correct Ac on class based
on [Link] configura on.

In Struts 1, Ac onServlet checks the struts-confi[Link] file to find the corresponding ac on.
3. Mapping the Request to an Ac on Class

The controller (FilterDispatcher) reads the [Link] configura on file.

It iden fies the correct Ac on class to execute.

Example [Link] Configura on:

<struts>

<package name="default" extends="struts-default">

<ac on name="login" class="[Link] [Link] on">

<result name="success">[Link]</result>

<result name="error">[Link]</result>

</ac on>

</package>

</struts>

4. Execu ng the Ac on Class

The iden fied Ac on class is executed.

It processes user input, interacts with the Model (business logic/database), and determines the next
view (JSP page).

Example Ac on Class (LoginAc [Link]):

import [Link] onSupport;

public class LoginAc on extends Ac onSupport {

private String username;

private String password;

public String execute() {

if ("admin".equals(username) && "1234".equals(password)) {

return "success"; // Forward to [Link]


} else {

return "error"; // Forward to [Link]

// Ge ers and Se ers

public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

5. Invoking the Business Logic (Model Layer)

The Ac on class may interact with the Model layer to fetch or store data in a database.

This can be done using JDBC, Hibernate, or service classes.

Example Model Class ([Link]):

public class User {

private String username;

private String password;

// Constructor

public User(String username, String password) {

[Link] = username;

[Link] = password;

// Ge ers and Se ers

public String getUsername() { return username; }


public String getPassword() { return password; }

6. Returning the Result to View (JSP)

The Ac on class returns a result string ("success" or "error"), which is mapped in [Link] to a
corresponding JSP page.

The JSP file uses Struts tags to display dynamic data.

Example View ([Link]):

<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<body>

<h2>Welcome, <s:property value="username"/>!</h2>

</body>

</html>

7. Response Sent Back to the User

The Struts framework processes the result and sends the appropriate JSP response back to the client.

The cycle completes when the user receives the output.

Struts Control Flow Diagram

[Client Request] ---> [Struts FilterDispatcher] ---> [Ac on Class]

| |
v v

[Business Logic] ---> [Model (Database)]

[Return Result]

[View (JSP)]

[Response to Client]

Advantages of Struts Control Flow

✔ Centralized Request Handling – Struts manages all requests via a single controller.

✔ Separa on of Concerns – Clear dis nc on between Model, View, and Controller.

✔ Reusability – Components like Ac on classes can be reused across the applica on.

✔ Extensibility – Can integrate with frameworks like Hibernate and Spring.

Steps to Build a Struts Applica on

Step 1: Set Up Development Environment

Prerequisites

JDK (Java Development Kit) installed (JDK 8 or later).

Apache Tomcat as a servlet container.

Eclipse IDE with Struts libraries.

Struts 2 Core Libraries (Download from Struts Official Website).


Step 2: Create a New Struts Project in Eclipse

1. Open Eclipse → Click File → New → Dynamic Web Project.

2. Enter Project Name (e.g., StrutsApp).

3. Select Apache Tomcat as Target Run me.

4. Click Finish to create the project.

5. Add Struts libraries ([Link], [Link], commons-fi[Link], etc.) to the lib folder
under WEB-INF.

Step 3: Configure [Link] (Deployment Descriptor)

This file is required to define the Struts framework in the applica on.

Loca on: WebContent/WEB-INF/[Link]

<web-app>

<filter>

<filter-name>struts2</filter-name>

<filter-class>[Link]</filter-class>

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pa ern>/*</url-pa ern>

</filter-mapping>

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Step 4: Create Struts Configura on File ([Link])


This file maps Ac on classes to their corresponding JSP pages.

Loca on: src/[Link]

<struts>

<package name="default" extends="struts-default">

<ac on name="login" class="[Link] [Link] on">

<result name="success">[Link]</result>

<result name="error">[Link]</result>

</ac on>

</package>

</struts>

Step 5: Create Model (Business Logic Layer)

The Model represents the data and business logic.

Example Model Class ([Link])

Loca on: src/com/model/[Link]

package [Link];

public class User {

private String username;

private String password;

// Constructor

public User(String username, String password) {

[Link] = username;

[Link] = password;

}
// Ge ers and Se ers

public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

Step 6: Create Ac on Class (Controller Layer)

The Ac on class processes user input and interacts with the Model.

Example Ac on Class (LoginAc [Link])

Loca on: src/com/ac on/LoginAc [Link]

package [Link] on;

import [Link] onSupport;

public class LoginAc on extends Ac onSupport {

private String username;

private String password;

public String execute() {

if ("admin".equals(username) && "1234".equals(password)) {

return "success"; // Forward to [Link]

} else {

return "error"; // Forward to [Link]

// Ge ers and Se ers


public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

Step 7: Create View (JSP Pages)

The View layer uses JSP with Struts UI Tags to display content dynamically.

1. Login Page ([Link])

Loca on: WebContent/[Link]

<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<body>

<h2>Struts Login Page</h2>

<s:form ac on="login">

<s:tex ield name="username" label="Username"/>

<s:password name="password" label="Password"/>

<s:submit value="Login"/>

</s:form>

</body>

</html>

2. Success Page ([Link])

Loca on: WebContent/[Link]

<%@ taglib uri="/struts-tags" prefix="s" %>


<html>

<body>

<h2>Welcome, <s:property value="username"/>!</h2>

</body>

</html>

3. Error Page ([Link])

Loca on: WebContent/[Link]

<html>

<body>

<h2>Invalid Creden als. Please Try Again.</h2>

<a href="[Link]">Go Back</a>

</body>

</html>

Step 8: Deploy and Run the Struts Applica on

1. Right-click the Project → Run As → Run on Server.

2. Select Apache Tomcat and click Finish.

3. Open a browser and enter:

h p://localhost:8080/StrutsApp/[Link]

4. Enter Username: admin and Password: 1234, then click Login.

5. If creden als are correct, [Link] is displayed; otherwise, [Link] appears.

Struts Project Structure in Eclipse

StrutsApp/

│── src/
│ ├── com/

│ │ ├── model/

│ │ │ ├── [Link]

│ │ ├── ac on/

│ │ │ ├── LoginAc [Link]

│── WebContent/

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│── WEB-INF/

│ ├── lib/ (Struts JAR files)

│ ├── [Link]

│ ├── [Link]

Advantages of Struts Applica on Development

✔ MVC-Based Structure – Ensures separa on of concerns.

✔ Reusable Components – Ac on classes and Struts tags simplify development.

✔ Centralized Configura on – [Link] makes request handling easier.

✔ Easy Integra on – Works with Hibernate, Spring, and other frameworks.

Introduc on to Struts Valida on Framework

The Struts Valida on Framework is used to validate user input in web applica ons. It helps ensure
that data entered in forms meets the required criteria before processing.

Struts provides two types of valida on:

1. Declara ve Valida on (XML-based) – Uses valida [Link] file.

2. Programma c Valida on – Defined in the Ac on class.


Types of Valida on in Struts

1. Client-Side Valida on

Uses JavaScript to validate input before sending it to the server.

Faster but less secure (can be bypassed if JavaScript is disabled).

2. Server-Side Valida on

Performed in the Ac on class or valida [Link] file.

More secure as it prevents malicious input.

Step-by-Step Implementa on of Struts Valida on

Step 1: Configure Valida on in Struts XML

Ensure your [Link] is correctly configured for valida on.

Example [Link] Configura on:

<struts>

<package name="default" extends="struts-default">

<ac on name="register" class="[Link] [Link] on">

<result name="success">[Link]</result>

<result name="input">[Link]</result>

</ac on>

</package>

</struts>
If valida on fails, Struts redirects to the input page ([Link]).

Step 2: Create the Ac on Class with Valida on

Loca on: src/com/ac on/RegisterAc [Link]

package [Link] on;

import [Link] onSupport;

public class RegisterAc on extends Ac onSupport {

private String username;

private String password;

private String email;

private int age;

public String execute() {

return "success";

// Ge ers and Se ers

public String getUsername() { return username; }

public void setUsername(String username) { [Link] = username; }

public String getPassword() { return password; }

public void setPassword(String password) { [Link] = password; }

public String getEmail() { return email; }

public void setEmail(String email) { [Link] = email; }

public int getAge() { return age; }

public void setAge(int age) { [Link] = age; }


// Custom Valida on (Programma c)

public void validate() {

if (username == null || [Link]().isEmpty()) {

addFieldError("username", "Username is required.");

if ([Link]() < 6) {

addFieldError("password", "Password must be at least 6 characters.");

if (![Link]("@")) {

addFieldError("email", "Invalid email format.");

if (age < 18) {

addFieldError("age", "Age must be 18 or above.");

validate() method ensures the fields meet the valida on criteria.

If valida on fails, addFieldError() adds an error message.

Step 3: Create the Valida on File (RegisterAc on-valida [Link])

Instead of using validate() in the Ac on class, we can define valida on rules declara vely.

Loca on: src/com/ac on/RegisterAc on-valida [Link]

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN"

"h p://[Link]/dtds/[Link]">

<validators>

<field name="username">
<field-validator type="required">

<message>Username is required.</message>

</field-validator>

</field>

<field name="password">

<field-validator type="stringlength">

<param name="minLength">6</param>

<message>Password must be at least 6 characters.</message>

</field-validator>

</field>

<field name="email">

<field-validator type="email">

<message>Invalid email format.</message>

</field-validator>

</field>

<field name="age">

<field-validator type="int">

<param name="min">18</param>

<message>Age must be 18 or above.</message>

</field-validator>

</field>

</validators>

This XML file automa cally validates the form fields without wri ng Java code.

Struts automa cally checks valida on rules when submi ng the form.

Step 4: Create the View (JSP Form with Struts Tags)

Loca on: WebContent/[Link]


<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<body>

<h2>Struts Valida on Example</h2>

<s:form ac on="register">

<s:tex ield name="username" label="Username"/>

<s:fielderror fieldName="username"/>

<s:password name="password" label="Password"/>

<s:fielderror fieldName="password"/>

<s:tex ield name="email" label="Email"/>

<s:fielderror fieldName="email"/>

<s:tex ield name="age" label="Age"/>

<s:fielderror fieldName="age"/>

<s:submit value="Register"/>

</s:form>

</body>

</html>

<s:fielderror> displays valida on errors next to each field.

Step 5: Create Success Page ([Link])

Loca on: WebContent/[Link]


<html>

<body>

<h2>Registra on Successful!</h2>

</body>

</html>

Struts Valida on Control Flow

1. User submits the form ([Link]).

2. Struts framework checks valida on rules in valida [Link] or validate() method.

3. If valida on fails, the user is redirected to [Link] with error messages.

4. If valida on passes, the user is redirected to [Link].

Advantages of Struts Valida on Framework

✔ Automa c Valida on – No need to write manual valida on logic.

✔ Reusable Rules – valida [Link] can be reused across mul ple Ac on classes.

✔ Custom Error Messages – Display meaningful valida on errors.

✔ Supports Both Client & Server-Side Valida on – More flexibility.

You might also like