# Trending December 2023 # Python Queue: Fifo, Lifo Example # Suggested January 2024 # Top 20 Popular

You are reading the article Python Queue: Fifo, Lifo Example updated in December 2023 on the website Minhminhbmm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Python Queue: Fifo, Lifo Example

What is Python Queue?

A queue is a container that holds data. The data that is entered first will be removed first, and hence a queue is also called “First in First Out” (FIFO). The queue has two ends front and rear. The items are entered from the rear and removed from the front side.

In this Python tutorial, you will learn:

How does Python Queue Work?

The queue can be easily compared with the real-world example the line of people waiting in a queue at the ticket counter, the person standing first will get the ticket first, followed by the next person and so on. The same logic goes for the queue data structure too.

Here is a diagrammatic representation of queue:

The Rear represents the point where the items are inserted inside the queue. In this example, 7 is value for that.

The Front represents the point where the items from the queue will be removed. If you remove an item from the queue, the first element you will get is 1, as shown in the figure.

Item 1 was the first one to be inserted in the queue, and while removing it is the first one to come out. Hence the queue is called FIRST IN FIRST OUT (FIFO)

In a queue, the items are removed in order and cannot be removed from in between. You just cannot remove the item 5 randomly from the queue, to do that you will have to remove all the items before 5. The items in queue will be removed in the order they are inserted.

Types of Queue in Python

There are mainly two types of queue in Python:

First in First out Queue: For this, the element that goes first will be the first to come chúng tôi work with FIFO, you have to call Queue() class from queue module.

Last in First out Queue: Over here, the element that is entered last will be the first to come chúng tôi work with LIFO, you have to call LifoQueue() class from the queue module.

Python queue Installation

It is very easy to work with queue in python. Here are the steps to follow to make use of queue in your code.

Step 1) You just have to import the queue module, as shown below:

import queue

The module is available by default with python, and you don’t need any additional installation to start working with the queue. There are 2 types of queue FIFO (first in first out) and LIFO (last in first out).

Step 2) To work with FIFO queue , call the Queue class using the queue module imported as shown below:

import queue q1 = queue.Queue()

Step 3) To work with LIFO queue call the LifoQueue() class as shown below:

import queue q1 = queue.LifoQueue() Methods available inside Queue and LifoQueue class

Following are the important methods available inside Queue and LifoQueue class:

put(item): This will put the item inside the queue.

get(): This will return you an item from the queue.

empty(): It will return true if the queue is empty and false if items are present.

qsize(): returns the size of the queue.

full(): returns true if the queue is full, otherwise false.

First In First Out Queue Example

In the case of first in first out, the element that goes first will be the first to come out.

Add and item in a queue

Let us work on an example to add an item in a queue. To start working with the queue, first import the module queue, as shown in the example below.

To add an item , you can make use of put() method as shown in the example:

import queue q1 = queue.Queue() q1.put(10) #this will additem 10 to the queue.

By default, the size of the queue is infinite and you can add any number of items to it. In case you want to define the size of the queue the same can be done as follows

import queue q1 = queue.Queue(5) #The max size is 5. q1.put(1) q1.put(2) q1.put(3) q1.put(4) q1.put(5) print(q1.full()) # will return true.

Output:

True

Now the size of the queue is 5, and it will not take more than 5 items, and the method q1.full() will return true. Adding any more items will not execute the code any further.

Remove an item from the queue

To remove an item from the queue, you can use the method called get(). This method allows items from the queue when called.

The following example shows how to remove an item from the queue.

import queue q1 = queue.Queue() q1.put(10) item1 = q1.get() print('The item removed from the queue is ', item1)

Output:

The item removed from the queue is 10 Last In First Out queue Example

In the case of last in the first out queue, the element that is entered last will be the first to come out.

To work with LIFO, i.e., last in the first out queue, we need to import the queue module and make use of the LifoQueue() method.

Add and item in a queue

Here we will understand how to add an item to the LIFO queue.

import queue q1 = queue.LifoQueue() q1.put(10)

You have to use the put() method on LifoQueue, as shown in the above example.

Remove an item from the queue

To remove an item from the LIFOqueue you can make use of get() method .

import queue q1 = queue.LifoQueue() q1.put(10) item1 = q1.get() print('The item removed from the LIFO queue is ', item1) Output: The item removed from the LIFO queue is 10 Add more than 1 item in a Queue

In the above examples, we have seen how to add a single item and remove the item for FIFO and LIFOqueue. Now we will see how to add more than one item and also remove it.

Add and item in a FIFOqueue import queue q1 = queue.Queue() for i in range(20): q1.put(i) # this will additem from 0 to 20 to the queue Remove an item from the FIFOqueue import queue q1 = queue.Queue() for i in range(20): q1.put(i) # this will additem from 0 to 20 to the queue while not q1.empty(): print("The value is ", q1.get()) # get() will remove the item from the queue.

Output:

The value is 0 The value is 1 The value is 2 The value is 3 The value is 4 The value is 5 The value is 6 The value is 7 The value is 8 The value is 9 The value is 10 The value is 11 The value is 12 The value is 13 The value is 14 The value is 15 The value is 16 The value is 17 The value is 18 The value is 19 Add and item in a LIFOqueue import queue q1 = queue.LifoQueue() for i in range(20): q1.put(i) # this will additem from 0 to 20 to the queue Remove an item from the LIFOqueue import queue q1 = queue.LifoQueue() for i in range(20): q1.put(i) # this will additem from 0 to 20 to the queue while not q1.empty(): print("The value is ", q1.get()) # get() will remove the item from the queue.

Output:

The value is 19 The value is 18 The value is 17 The value is 16 The value is 15 The value is 14 The value is 13 The value is 12 The value is 11 The value is 10 The value is 9 The value is 8 The value is 7 The value is 6 The value is 5 The value is 4 The value is 3 The value is 2 The value is 1 The value is 0 Sorting Queue

Following example shows the queue chúng tôi algorithm used for sorting is bubble sort.

import queue q1 = queue.Queue() #Addingitems to the queue q1.put(11) q1.put(5) q1.put(4) q1.put(21) q1.put(3) q1.put(10) #using bubble sort on the queue n = q1.qsize() for i in range(n): x = q1.get() # the element is removed for j in range(n-1): y = q1.get() # the element is removed q1.put(y) #the smaller one is put at the start of the queue else: q1.put(x) # the smaller one is put at the start of the queue x = y # the greater one is replaced with x and compared again with nextelement q1.put(x) while (q1.empty() == False): print(q1.queue[0], end = " ") q1.get()

Output:

3 4 5 10 11 21 Reversing Queue

To reverse the queue, you can make use of another queue and recursion.

The following example shows how to get the queue reversed.

Example:

import queue q1 = queue.Queue() q1.put(11) q1.put(5) q1.put(4) q1.put(21) q1.put(3) q1.put(10) def reverseQueue (q1src, q2dest) : buffer = q1src.get() if (q1src.empty() == False) : reverseQueue(q1src, q2dest) #using recursion q2dest.put(buffer) return q2dest q2dest = queue.Queue() qReversed = reverseQueue(q1,q2dest) while (qReversed.empty() == False): print(qReversed.queue[0], end = " ") qReversed.get()

Output:

10 3 21 4 5 11 Summary:

A queue is a container that holds data. There are two types of Queue, FIFO, and LIFO.

For a FIFO (First in First out Queue), the element that goes first will be the first to come out.

For a LIFO (Last in First out Queue), the element that is entered last will be the first to come out.

An item in a queue is added using the put(item) method.

To remove an item, get() method is used.

You're reading Python Queue: Fifo, Lifo Example

## How Does Kafka Queue Works In Detail?

Introduction to Kafka Queue

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of Kafka Queue

As such, there is no exact syntax exist for Kafka queues. To work with the Kafka queues, we need to know the complete architecture of the Kafka streaming solution. Similarly, we need to also know how the data is flowing in the Kafka environment. In Kafka queues, we are using it with the number of consumers like the Kafka consumer group. As per the requirement or need, we need to define the queue configuration of the Kafka environment. As per the defined architecture, we need to set the number queue configuration and define it as per the requirement. In Kafka, it will support both the message queue as well as the publish & subscribe technique (It will depend on the architecture and requirement).

How Kafka Queue Works?

Given below are the lists of properties that would be helpful to tune the queue in the Kafka environment.

1. Property name: queued.max.requests

The default value for this property: 500.

2. Property name: controller.message.queue.size

The default value for this property: 10.

Explanation: The chúng tôi property will help to define the buffer size value. The same buffer size value pointing to the controller-to-broker channels.

3. Property name: queued.max.message.chunks

The default value for this property: 10.

Explanation: The queued.max.message.chunks property will help to define the maximum number of messages group, or chunks will be buffered for the consumption. As per the requirement, we can define the value of this. The single chunk will be able to fetch the data as per the fetch.message.max.bytes.

4. Property name: queue.buffering.max.ms

The default value for this property: 5000.

Explanation: This is the time value we are defining for the chúng tôi property. It would define the time to hold the buffer data when it will use the async mode. Let’s take an example; if we set the value 200, then it will try to do the batch together at the 200 Ms of the messages or the data to send at a single point. So thus, it will be able to improve the throughput. But once the throughput increases, the latency of the additional messages will increase due to the buffering.

5. Property name: queue.buffering.max.messages

The default value for this property: 10000.

Explanation: It will help to define the number of unsent messages. It will be queued up to the producer. It will happen when we are using async mode. It might happen either the Kafka producer will be blocked, or the data will be dropped.

6. Property name: queue.enqueue.timeout.ms

The default value for this property: -1.

Explanation: It will define the amount of that will be hold before dropping the messages. When we are running in the async mode, then the buffer will reach to queue. If we will set the value as the “0”, it will be queued immediately. In other words, it will drop if the queue is full. The producer will send the call to never block. If we set the value as “-1”, then the producer will block, and it will not be able to drop the request.

7. Property name: batch.num.messages

The default value for this property: 200.

Explanation: The number of messages to send in one batch when using async mode. The producer will wait until either this number of messages is ready to send or chúng tôi is reached when we are using the async mode then the batch.num.messages property will help to define the number of messages that will send in a single batch. The Kafka producer will wait until the number of messages is ready to send. In other words, it will also wait for the value which is defined under chúng tôi will be reached.

Example of Kafka Queue

Given below is the example of Kafka Queue:

As such, there is a specific command to work with the Kafka queue. It is just a technique that we need to understand and make the Kafka broker’s necessary changes. As per the above configuration property that we have shared.

Conclusion

We have seen the uncut concept of the “Kafka queue” with the proper explanation. For the Kafka broker, we need to tune the Kafka queue properties. When multiple consumers want to access a single topic, only a queue will come in a picture.

Recommended Articles

This is a guide to Kafka Queue. Here we discuss the introduction, how Kafka queue works? And an example for better understanding. You may also have a look at the following articles to learn more –

## Php Ajax Tutorial With Example

What is Ajax?

AJAX full form is Asynchronous JavaScript & XML. It is a technology that reduces the interactions between the server and client. It does this by updating only part of a web page rather than the whole chúng tôi asynchronous interactions are initiated by chúng tôi purpose of AJAX is to exchange small amounts of data with server without page refresh.

JavaScript is a client side scripting language. It is executed on the client side by the web browsers that support JavaScript.JavaScript code only works in browsers that have JavaScript enabled.

XML is the acronym for Extensible Markup Language. It is used to encode messages in both human and machine readable formats. It’s like HTML but allows you to create your custom tags. For more details on XML, see the article on XML

Why use AJAX?

It allows developing rich interactive web applications just like desktop applications.

Validation can be performed done as the user fills in a form without submitting it. This can be achieved using auto completion. The words that the user types in are submitted to the server for processing. The server responds with keywords that match what the user entered.

It can be used to populate a dropdown box depending on the value of another dropdown box

Data can be retrieved from the server and only a certain part of a page updated without loading the whole page. This is very useful for web page parts that load things like

Tweets

Commens

Users visiting the site etc.

How to Create an PHP Ajax application

We will create a simple application that allows users to search for popular PHP MVC frameworks.

Our application will have a text box that users will type in the names of the framework.

We will then use mvc AJAX to search for a match then display the framework’s complete name just below the search form.

Step 1) Creating the index page

chúng tôi

HERE,

“onkeyup=”showName(this.value)”” executes the JavaScript function showName everytime a key is typed in the textbox.

This feature is called auto complete

Step 2) Creating the frameworks page

chúng tôi

<?php \$frameworks = array("CodeIgniter","Zend Framework","Cake PHP","Kohana") ; \$name = \$_GET["name"]; \$match = ""; for (\$i = 0; \$i < count(\$frameworks); \$i++) { if (strtolower(\$name) == strtolower(substr(\$frameworks[\$i], 0, strlen(\$name)))) { if (\$match == "") { \$match = \$frameworks[\$i]; } else { \$match = \$match . " , " . \$frameworks[\$i]; } } } } echo (\$match == "") ? 'no match found' : \$match; Step 3) Creating the JS script

auto_complete.js

function showName(str){ if (str.length == 0){ document.getElementById("txtName").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari } else {// code for IE6, IE5 } } } }

HERE,

“if (str.length == 0)” check the length of the string. If it is 0, then the rest of the script is not executed.

“if (window.XMLHttpRequest)…” Internet Explorer versions 5 and 6 use ActiveXObject for AJAX implementation. Other versions and browsers such as Chrome, FireFox use XMLHttpRequest. This code will ensure that our application works in both IE 5 & 6 and other high versions of IE and browsers.

Step 4) Testing our PHP Ajax application

Type the letter C in the text box You will get the following results.

The above example demonstrates the concept of AJAX and how it can help us create rich interaction applications.

Summary

AJAX is the acronym for Asynchronous JavaScript and XML

AJAX is a technology used to create rich interaction applications that reduce the interactions between the client and the server by updating only parts of the web page.

Internet Explorer version 5 and 6 use ActiveXObject to implement AJAX operations.

Internet explorer version 7 and above and browsers Chrome, Firefox, Opera, and Safari use XMLHttpRequest.

## Requirements Analysis Techniques With Example: Complete Tutorial

As a Business Analyst, requirement analysis is the most important part of your Job. It will help you determining the actual needs of stakeholders. At the same time, enable you to communicate with the stakeholders in a language they understand (like charts, models, flow-charts,) instead of complex text.

A requirement analysis has a

Specific Goal

Specific Input

Specific Output

Uses resources

Has a number of activities to be performed in some order

May affect more than one organization unit

Creates value of some kind for the customer

1

Monday

Learn More

On Monday’s Website

Time Tracking

Yes

Drag & Drop

Yes

Free Trial

Forever Free Plan

2

Teamwork

Learn More

On Teamwork’s Website

Time Tracking

Yes

Drag & Drop

Yes

Free Trial

Forever Free Plan

3

JIRA Software

Learn More

On Jira Software Website

Time Tracking

Yes

Drag & Drop

Yes

Free Trial

Forever Free Plan

Requirement Analysis Techniques

Requirement analysis techniques are mainly used to map the business workflow so that you can analyze, understand and make required changes to that workflow or process.

There are various requirement analyzing techniques that can be used as per the software development process like

Business process modeling notation (BPMN)

BPMN (Business Process Modeling & Notation) is a graphical representation of your business process using simple objects, which helps the organization to communicate in a standard manner. Various objects used in BPMN includes

Flow objects

Connecting objects

Swim lanes

Artifacts.

A well design BPMN model should be able to give the detail about the activities carried out during the process like,

Who is performing these activities?

What data elements are required for these activities?

The biggest benefit of using BPMN is that it is easier to share, and most modeling tools support BPMN.

UML (Unified Modeling Language)

UML is a modelling standard primarily used for specification, development, visualization and documenting of software system. To capture important business process and artifacts UML provides objects like

State

Object

Activity

Class diagram

There are 14 UML diagrams that help with modelling like the use case diagram, interaction diagram, class diagram, component diagram, sequence diagram, etc. UML models are important in the IT segment as it becomes the medium of communication between all stakeholders. A UML-based business model can be a direct input to a requirements tool. A UML diagram can be of two type’s Behavioral model and Structural model. A behavioral model tries to give information about what the system do while a structural model will give what is the system consist of.

Flow chart technique

Data flow diagram

Data flow diagrams show how data is processed by a system in terms of inputs and outputs. Components of data flow diagram includes

Process

Flow

Store

Terminator

A logical data flow diagram shows system’s activities while a physical data flow diagram shows a system’s infrastructure. A data flow diagram can be designed early in the requirement elicitation process of the analysis phase within the SDLC (System Development Life Cycle) to define the project scope. For easy analyzing a data flow diagram can be drilled down into its sub-processes known as “levelled DFD”.

Role Activity Diagrams- (RAD)

Role activity diagram is similar to flowchart type notation. In Role Activity Diagram, role instances are process participants, which has start and end state. RAD requires a deep knowledge of process or organization to identify roles. The components of RAD includes

Activities

External events

States

Roles group activities together into units of responsibility, according to the set of responsibility they are carrying out. An activity can be carried out in isolation with a role, or it may require coordination with activities in other roles.

External events are the points at which state changes occur.

States are useful to map activities of a role as it progresses from state to state. When a particular state is reached, it indicates that a certain goal has been achieved.

RAD is helpful in supporting communication as it is easy to read and present a detailed view of the process and permitting activities in parallel.

Gantt Charts

A Gantt chart is a graphical representation of a schedule that helps to coordinate, plan and track specific tasks in a project. It represents the total time span of the object, broken down into increments. A Gantt chart represents the list of all task to be performed on the vertical axis while, on the horizontal axis, it list the estimate activity duration or the name of the person allocated to the activity. One chart can demonstrate many activities.

IDEF (Integrated Definition for Function Modeling)

IDEF or Integrated Definition for Function Modeling is a common name referred to classes of enterprise modeling languages. It is used for modeling activities necessary to support system analysis, design or integration. There are about 16 methods for IDEF, the most useful versions of IDEF are IDEF3 and IDEF0.

Colored Petri Nets (CPN)

CPN or colored petri nets are graphically oriented language for specification, verification, design and simulation of systems. Colored Petri Nets is a combination of graphics and text. Its main components are Places, Transitions, and Arcs.

Petri nets objects have specific inscription like for

Places: It has inscription like .Name, .Color Set, .Initial marking etc. While

Transition : lt has inscription like .Name (for identification) and .Guard (Boolean expression consist of some of the variables)

Arcs: It has inscription like .Arc. When the arc expression is assessed, it yields multi-set of token colors.

Workflow Technique

Workflow technique is a visual diagram that represent one or more business processes to clarify understanding of the process or to make process improvement recommendations. Just like other diagrams like flowcharting, UML activity and process map, the workflow technique is the oldest and popular technique. It is even used by BA for taking notes during requirements elicitation. The process comprises of four stages

Information Gathering

Workflow Modeling

Business process Modeling

Implementation, Verification & Execution

Object oriented methods

Object-oriented modeling method uses object oriented paradigm and modeling language for designing a system. It emphasis on finding and describing the object in the problem domain. The purpose of object oriented method is

To help characterizing the system

To know what are the different relevant objects

How do they relate to each other

How to specify or model a problem to create effective design

To analyze requirements and their implications

This method is applicable to the system which has dynamic requirements (changes frequently). It is a process of deriving use cases, activity flow, and events flow for the system. Object oriented analysis can be done through textual needs, communication with system stakeholder and vision document.

The object has a state, and state changes are represented by behavior. So, when the object receives a message, state changes through behavior.

Gap Analysis

Gap Analysis is the technique used to determine the difference between the proposed state and current state for any business and its functionalities. It answers questions like what is the current state of the project? Where do we want to be? etc. Various stages of Gap Analysis include

Review System

Development Requirements

Comparison

Implications

Recommendations

## How To Use Variables Sas Rename With Example?

Introduction to SAS Rename

The SAS rename is the feature for changing the variable’s name or the variable list already declared in the SAS input data set or in the data step created by the new set of variables. It allows you to replace old variable names in programming statements by changing one or more variables written into the output directory.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Overview of SAS Rename

The rename is a type of function that can be used for more than one variable in a SAS dataset, and SAS users will refer to it as such. Renaming column variables will use the datas like NHANES, but the code of the data registration is not correctly called for the column names. This is nearly impossible for the recoding data columns. It decodes the datas by using the more straightforward format that assists and is associated with the sequence number of the SAS issues and the spaces between the original data content and duplicate contents.

We can enclose the text from the data label using the single and double quotation Rename option, which tells SAS to change the name of the two variables from within the parentheses as long as the space separates each pair of the old and new variables.

How to Use Variables SAS Rename?

We can use the rename function with the SAS dataset for the column variables from the NHANES data, but the data code is registered incorrectly. The specified column names are so long, and it’s nearly impossible to recode the data from one format to another more straightforward format. Respondent and correct sequence numbers to the ID with SAS having issues on the spaces from the original name to the duplicate name with exact sequence steps.

Steps to create the variable SAS rename:

1. Navigate to the below link.

3. After successfully logging in, type the below code for creating the data set and Proc SQL.

4. data First;

5. input emp_id \$ emp_name \$ emp_dob \$;

6. datalines;

7. 1234 Raman 10051989

8. 5 Srew 1234521

9. 6 rtw 10454

10. ;

11.

12. proc sql;

13. insert into First

14. set emp_id=1234,

15. emp_namename=’Raman’,

16. emp_dob=10051989

18. the title “Welcome To My Domain”;

19. select emp_name format=\$20.,

20. emp_id format=\$15.,

21. emp_dob format=comma15.0

22. from First;

Output:

It helps create the dataset along with PROC SQL with the variable declaration.

Then by using the below code to change the variable or column name like emp_name, it is changed to name by using the below code.

Code:

data First; set First; rename emp_name = Name; run;

Output:

The name is successfully changed and displayed on the output tab.

SAS Rename Statement

The SAS rename statement is specified with the new names for the required variables in the output console for SAS data sets; it is valid in the DATA step. The statement category is the CAS, denoted by the data and information, and it’s declared using the Declarative type. Rename parameters like old and new names with the specified arguments and enable the name change for one or more variables on the list that will combine the variables and variable lists. The new variable name is declared by the user end. Then, it will be executed and written into the output directory dataset by using the old variable names in programming statements for the current data step. Rename the values and apply them to all the output data sets.

Generally, the Rename statement, which affects the datasets, is already opened in the output mode, which must continue to rename the old variable names in the programming statements for the current DATA step. After the output data is created, the SET statement’s new variable names rename the input data set variables. We can set and use the new names in the programming statements of the current data step of renaming the variables, which helps to write the datas in the file management task. Using the datasets procedure or accessing the variables through the SAS windowing interface for the method is more straightforward and does not require data step processing. Using the change statement, we can call the datasets procedure for renaming the variables for setting the same library in the SAS.

Example of SAS Rename

Given below is the example of SAS Rename:

Code:

DATA Second; INPUT Rollno \$ ID \$ Name \$; DATALINES; 001 9184321123 Siva 002 9212434 Raman 003 9351251 Sivaraman ; RUN; PROC SQL; CREATE TABLE bckup AS SELECT * FROM Second; QUIT; PROC PRINT vars = bckup; RUN;

Output:

Code:

data Second; set Second; rename ID = MobileNumber; run;

Output:

The above codes are the primary example for renaming the variables, columns, and data types.

Here the Rename option uses the dataset option to pass the input dataset along with the variable SET statement and the output dataset.

Create a table on the proc sql using the rename keyword; we can rename the old value to a new value.

Conclusion

The SAS Rename is the type of option that can be used in the dataset option for both the input dataset, which passed the SET statement, and the output dataset. The Rename option will follow the keep and drop options using the existing variable name.

Recommended Articles

This is a guide to SAS Rename. Here we discuss the introduction, how to use variables SAS rename? And examples, respectively. You may also have a look at the following articles to learn more –

## Mvc Architecture In Java With Jsp Application Design Example

What is MVC?

MVC is an architecture that separates business logic, presentation and data. In MVC,

M stands for Model

V stands for View

C stands for controller.

MVC Architecture Diagram

Model Layer

This is the data layer which consists of the business logic of the system.

It consists of all the data of the application

It also represents the state of the application.

It consists of classes which have the connection to the database.

The controller connects with model and fetches the data and sends to the view layer.

The model connects with the database as well and stores the data into a database which is connected to it.

View Layer

This is a presentation layer.

It consists of HTML, JSP, etc. into it.

It normally presents the UI of the application.

It is used to display the data which is fetched from the controller which in turn fetching data from model layer classes.

This view layer shows the data on UI of the application.

Controller Layer

It acts as an interface between View and Model.

It intercepts all the requests which are coming from the view layer.

It receives the requests from the view layer and processes the requests and does the necessary validation for the request.

This requests is further sent to model layer for data processing, and once the request is processed, it sends back to the controller with required information and displayed accordingly by the view.

Advantages of MVC Architecture

Easy to maintain

Easy to extend

Easy to test

Navigation control is centralized

Example of JSP Application Design with MVC Architecture

In this example, we are going to show how to use MVC architecture in JSP.

We are taking the example of a form with two variables “email” and “password” which is our view layer.

This mvc_servlet is controller layer. Here in mvc_servlet the request is sent to the bean object which act as model layer.

The email and password values are set into the bean and stored for further purpose.

From the bean, the value is fetched and shown in the view layer.

Mvc_example.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

View Layer:

Code Line 10-15: Here we are taking a form which has two fields as parameter “email” and “password” and this request need to be forwarded to a controller Mvc_servlet.java, which is passed in chúng tôi method through which it is passed is POST method.

Mvc_servlet.java

package demotest; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; /** * Servlet implementation class Mvc_servlet */ public class Mvc_servlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Mvc_servlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email=request.getParameter("email"); String password=request.getParameter("password"); TestBean testobj = new TestBean(); testobj.setEmail(email); testobj.setPassword(password); request.setAttribute("gurubean",testobj); RequestDispatcher rd=request.getRequestDispatcher("mvc_success.jsp"); rd.forward(request, response); } }

Explanation of the code:

Controller layer

Code Line 14:mvc_servlet is extending HttpServlet.

Code Line 26: As the method used is POST hence request comes into a doPost method of the servlet which process the requests and saves into the bean object as testobj.

Code Line 34: Using request object we are setting the attribute as gurubean which is assigned the value of testobj.

Code Line 35: Here we are using request dispatcher object to pass the success message to mvc_success.jsp

TestBean.java

package demotest; import java.io.Serializable; public class TestBean implements Serializable{ public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String email="null"; private String password="null"; }

Explanation of the code:

Model Layer:

Code Line 7-17: It contains the getters and setters of email and password which are members of Test Bean class

Code Line 19-20: It defines the members email and password of string type in the bean class.

Mvc_success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" <% TestBean testguru=(TestBean)request.getAttribute("gurubean"); out.print("Welcome, "+testguru.getEmail());

Explanation of the code:

Code Line 12: we are getting the attribute using request object which has been set in the doPost method of the servlet.

Code Line 13: We are printing the welcome message and email id of which have been saved in the bean object

Output:

When you execute the above code, you get the following output:

Output:

Summary

In this article, we have learnt about the MVC i.e. Model View Controller architecture.

JSP plays the role of presentation of the data and controller. It is an interface between model and view while model connects both to the controller as well as the database. Main business logic is present in the model layer.

Update the detailed information about Python Queue: Fifo, Lifo Example on the Minhminhbmm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!