0% found this document useful (0 votes)
5 views28 pages

Unit 4 Module

The document outlines the curriculum for a web technology course, focusing on web application development using the Struts framework and MVC architecture. It covers various types of web applications, the development process, methodologies, and specific features of the Struts framework, including its tags and components. Additionally, it details the stages of web development from project definition to maintenance, emphasizing the importance of user interface design and content creation.

Uploaded by

anaikutti329
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)
5 views28 pages

Unit 4 Module

The document outlines the curriculum for a web technology course, focusing on web application development using the Struts framework and MVC architecture. It covers various types of web applications, the development process, methodologies, and specific features of the Struts framework, including its tags and components. Additionally, it details the stages of web development from project definition to maintenance, emphasizing the importance of user interface design and content creation.

Uploaded by

anaikutti329
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

Regulation 2023 Academic Year: 2025-2026

DEPARTMENT OF CSE & IT


23CS4402 – WEB TECHNOLOGY
UNIT IV - WEB APPLICATION DEVELOPMENT
MATERIAL
Introduction to Struts, Struts framework, Process, MVC Architecture for strut Environment, Handling
exceptions in struts, validation and development in struts, Data Management and Database Integration.
4.1 Web Application Development
Web applications are computer applications that the user does not run directly on their own
computer, but rather accesses through a Web browser. The GUI is provided by the Web browser
(usually as some form of HTML), and all of the application's processing is done either on the browser
with JavaScript, on the Web server itself, or on both. This means that Web application development
is the development of network-based applications, including server-side (i.e., on the Web server) and
client- side (i.e., on the Web browser) programming.
Web application development is the process of using client-side and server-side programming
to develop an application accessible over a web browser. Developers begin with ideating a web
application based on finding a solution to a specific problem and move on to design the app, choose
the right framework to develop the web app, test it and finally deploy it.
Web apps are essentially an application software that is stored on a remote server provided by a
third-party and can be used directly from your browser, without having to download anything.
4.1.1 Types of Web Applications
 Static web applications
 Dynamic web applications
 Ecommerce web applications
 Portal web applications
 Content Management System
 Progressive web applications
Static web applications
Static web apps are more like a collection of static web pages that display the same information
to every visitor. They are built using HTML and CSS and offer no interactivity. Since the pages in
static web app development are generated on the server end, there is no room for personalization.
Static web app pages are also very difficult to change or update.
Dynamic web applications
Dynamic web applications do not follow a pre-determined order of display but are instead
shaped by input on the client-side or server-side. These apps deploy a content management system or
CMS that modifies the app’s contents.
A wide number of programming languages including PHP and ASP to build a web app. These
apps require web hosting, databases and servers. While technically, all apps that aren’t static web apps,
are dynamic apps, there are some broader categories which make up for the rest of this list of types of
apps.
Ecommerce web applications
Electronic Commerce has unleashed yet another revolution, which is changing the way
business buys and sells products and services. It is associated with buying and selling of information,
products and services over computer communication networks.
E-Commerce (EC) helps conduct traditional commerce through new ways of transferring and
processing information, since it is information which is at the heart of any commercial activity.
Information is electronically transferred from computer to computer, in an automated way.
E-Commerce refers to the paperless exchange of business information using Electronic Data
Interchange, Electronic Mail, Electronic Bulletin Boards, Electronic Funds Transfer and other network-based
technologies.
Regulation 2023 Academic Year: 2025-2026

Portal web applications


A portal web app is a type of web application that allows users to log in to a secure area from a
home page. Take credit card payments for instance. Once a shopping website or a bill payment
website, and when it’s time to choose a credit card and make a payment, you are asked to log into the
credit card company’s web app to complete the payment.
Content Management System
A content management system or CMS allows even non-technical users to easily create and
update content online. From a simple blog to a more comprehensive website, a CMS allows users to
keep these assets up to date with the latest information. Creating such a system that simple non-
technical users can easily use requires special technologies best left to professional web app
developers.
Progressive web applications
Progressive web apps (PWAs) are not a classification of web applications. They are in fact, a
quantum leap in the field of web based application development. A PWA takes advantage of the latest
and best web application development frameworks and technologies to gives a product that combines
the very best of web apps and native mobile apps.
4.2 Web Application Development Process
Web development refers to building website and deploying on the web. Web development
requires use of scripting languages both at the server end as well as at client end.

Figure 4.1 web application development process


Web development process includes all the steps that are good to take to build an attractive,
effective and responsive website. These steps are shown in the following diagram:
Regulation 2023 Academic Year: 2025-2026
Figure 4.2 Stages of web development

Stage 1: Define project


The first step in the website development process is to define the goals of project. These
typically include:
Business details: Define the purpose, unique value proposition, mission, vision, etc.
Business goals: Set clear, measurable goals for website to develop the most effective strategy,
including the KPIs to measure performance.
Target audience: Define target audience and research their preferences, likes and dislikes, study their
online habits and more to get to know them and their expectations.
Competition: Research competition, analyzes strengths and weaknesses, and develops a plan to
position your brand on the market.
Stage 2: Plan Website
Define website’s layout from landing pages to product pages, key conversion points and more.
Create a sitemap: A sitemap is a bird’s eye view of your site that determines the list of pages, their
placement and relationship to each other on the website. It includes both user-facing elements and
those intended for web crawlers (such as Google). A site map helps define and organize your web
content, allowing your strategist and designer to go deeper into planning the look, feel and
functionality for each page.
A wireframe: A wireframe is the layout of each individual page of your site. It outlines and the
elements and content, from headlines to CTAs and subscription boxes. The wireframe should cover
both desktop and mobile versions.
Stage 3: Design Website
User Interface (UI) design stage to introduce branding and complete the look and feel of
website. Define each branding element, from color palette, logo and iconography to the images and
videos. These branding elements should remain consistent across all channels, from website to social
media pages, marketing materials, newsletters and more.
Stage 4: Create Content
In the website development process is to plan and create content. Depending on target
audience, content creation may include:
 Landing pages
 Product/service descriptions
 Testimonials
 Case studies
 Blog posts
 Videos
 Images
 Newsletters
 White papers
 Social media posts
Create content based on target audience. Research where they spend their time and define what
type of content they are most likely to interact and connect with.
Stage 5: Develop Website
Once defined set of goals, planned design, created your branding elements and devised a
content plan, it’s time for development. Need backend and frontend developers to build website, using
industry best practices and detailed specification documents. From the platform choose to different
features and functionalities, your website should be built with the ability to scale to match growth
potential.
Stage 6: Test Website
Regulation 2023 Academic Year: 2025-2026
The aim is to detect any issues such as broken links and compatibility with different devices to
ensure everything works properly. Use validators to check if the code follows the standards, test the
site’s speed and ensure it’s responsive on all devices.

Stage 7: Maintain Website


As your business grows may need to increase the number of pages, add more functionality, and
update features and more. Regular maintenance includes:
 Editing existing content
 Adding content
 Fixing bugs and issues
 Installing plugins
Modern web design trends are constantly changing, and new technology provides opportunities for
advanced features and functionalities. Hiring a professional web design agency can ensure brand is
never left in the dust by the competition.
4.2.1 Web Development Methodologies
A web development methodology helps developers break a project up into several stages and
each stage lays the foundation for next stage’s activities.
Some of the most common web development methodologies include:
 Agile: Agile is an umbrella term that describes a web development methodology recognized
for short cycles called “sprints.” These require less planning, flexibility and adaptability. Agile
methodology focuses on recommendations and user feedback to ensure high-quality project
delivery.
 Waterfall: With clearly defined stages completed in a sequence, Waterfall allows developers
to set objectives, deadlines and cost estimation.
 Iterative: Based on a cyclic process of prototyping, testing and analyzing, Iterative focuses on
metrics and data to change the website development process according to changing market
needs.
 Lean: Focused on eliminating anything that doesn’t add value to client, Lean uses short
development cycles, early testing and frequent client feedback.
 Scrum: A type of agile methodology, Scrum skips the documentation and specifications stage
and divides the developing process into sprints. The development team has more freedom to
decide how to deliver the final product with minimum input from the team manager.
 Kanban: Based on workflow visualization, Kanban boosts efficiency by limiting the amount
of work in progress and having no strict roles within a group.
 Extreme Programming: This methodology’s best practices include continuous testing and
planning, customer input and smaller, gradual releases.
4.3 Introduction to Struts
Struts is an open-source web application framework used for developing Java EE web
applications. It follows the Model-View-Controller (MVC) design pattern, which separates the
application logic into three components: Model (business logic), View (presentation layer), and
Controller (handles user input). Struts simplifies the development of web applications by providing
reusable components, configuration files, and tools for integrating with other frameworks.
4.3.1 Struts framework
Struts are a framework that promotes the use of the Model-View Controller architecture for
designing large scale applications. The framework includes a set of custom tag libraries and their
associated Java classes, along with various utility classes. The most powerful aspect of the Struts
framework is its support for creating and processing web-based forms.
Struts are an MVC implementation that uses Servlets 2.2 and JSP 1.1 tags, from the J2EE
specifications, as part of the implementation.
Regulation 2023 Academic Year: 2025-2026
It includes features like
 Action classes : Handle business logic and user input.
 Action Form : A JavaBean used to encapsulate form data.
 Struts Tags : Simplify the JSP page development.
 Interceptors : Provide a way to modify the execution of an action.
 Validation framework: Allows automatic validation of form data.
Struts also integrates well with other Java frameworks like Spring and Hibernate for handling business
logic and persistence, respectively.
4.3.2 Struts Tags
Almost all tags provided by the Struts framework use the following attributes:
Attribute used for
Id the name of a bean for temporary use by the tag
Name the name of a pre-existing bean for use with the tag
Property the property of the bean named in the name attribute for use with the tag
Scope the scope to search for the bean named in the name attribute
The Struts tag has a set of tags that makes it easy to control the flow of page execution. The struts tags are
 Struts – Control tags
 Struts – Data tags
 Struts – Form tags
 Struts – Ajax tags
Struts Control Tags
Struts control tags are used for manipulation and navigation of data from a collection. Some of the
important Struts control tags are:
 If and Else Tags
 Iterator Tags
 Merge Tag
 Append Tag
 Generator Tag
If and Else Tags
These tags perform basic condition flow found in every language. 'If' tag is used by itself or with 'Else If'
Tag and/or single/multiple 'Else' Tag as shown below
<s:if test = "%{false}">
<div>Will Not Be Executed</div>
</s:if>
<s:elseif test = "%{true}">
<div>Will Be Executed</div>
</s:elseif>
<s:else>
<div>Will Not Be Executed</div>
</s:else>

Iterator Tags
This iterator will iterate over a value. An iterable value can be either [Link] or
[Link] file. While iterating over an iterator, can use Sort tag to sort the result or SubSet tag to get a sub
set of the list or array. The following example retrieves the value of the getDays() method of the current object
on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator.
<s:iterator value = "days">
<p>day is: <s:property/></p>
</s:iterator>
Merge Tag
These merge tag takes two or more list as parameters and merge them all together as shown below
<s:merge var = "myMergedIterator">
<s:param value = "%{myList1}" />
Regulation 2023 Academic Year: 2025-2026
<s:param value = "%{myList2}" />
<s:param value = "%{myList3}" />
</s:merge>
<s:iterator value = "%{#myMergedIterator}">
<s:property />
</s:iterator>
The Append tag
These append tag take two or more lists as parameters and append them all together as shown below
<s:append var = "myAppendIterator">
<s:param value = "%{myList1}" />
<s:param value = "%{myList2}" />
<s:param value = "%{myList3}" />
</s:append>
<s:iterator value = "%{#myAppendIterator}">
<s:property />
</s:iterator>
The Generator Tag
These generator tags generate an iterator based on the val attribute supplied. The following generator
tag generates an iterator and prints it out using the iterator tag.
<s:generator val = "%{'aaa,bbb,ccc,ddd,eee'}">
<s:iterator>
<s:property /><br/>
</s:iterator>
</s:generator>
Struts Data Tags
The Struts data tags are primarily used to manipulate the data displayed on a page. Listed below are the
important data tags.
The Action Tag
This tag enables developers to call actions directly from a JSP page by specifying the action name and
an optional namespace. The body content of the tag is used to render the results from the Action. Any result
processor defined for this action in [Link] will be ignored, unless the execute Result parameter is specified.
<div>Tag to execute the action</div>
<br />
<s:action name = "actionTagAction" executeresult = "true" />
<br />
<div>To invokes special method in action class</div>
<br />
<s:action name = "actionTagAction!specialMethod" executeresult = "true" />
The Include Tag
These include will be used to include a JSP file in another JSP page.
<-- First Syntax -->
<s:include value = "[Link]" />
<-- Second Syntax -->
<s:include value = "[Link]">
<s:param name = "param1" value = "value2" />
<s:param name = "param2" value = "value2" />
</s:include>
<-- Third Syntax -->
<s:include value = "[Link]">
<s:param name = "param1">value1</s:param>
<s:param name = "param2">value2</s:param>
</s:include>
The Bean Tag
These bean tag instantiates a class that conforms to the JavaBeans specification. This tag has a body
Regulation 2023 Academic Year: 2025-2026
which can contain a number of Param elements to set any mutator methods on that class. If the var attribute is
set on the BeanTag, it will place the instantiated bean into the stack's Context.
<s:bean name = "[Link]" var = "counter">
<s:param name = "first" value = "20"/>
<s:param name = "last" value = "25" />
</s:bean>
The Date Tag
These date tag will allow you to format a Date in a quick and easy way. Specify a custom format (eg.
"dd/MM/yyyy hh:mm"), it must generate easy readable notations (like "in 2 hours, 14 minutes"), or it can just
fall back on a predefined format with key '[Link]' in your properties file.
<s:date name = "[Link]" format = "dd/MM/yyyy" />
<s:date name = "[Link]" format = "%{getText('[Link]')}" />
<s:date name = "[Link]" nice="true" />
<s:date name = "[Link]" />
The Param Tag
These p aram tag can be used to parameterize other tags. This tag has the following two parameters.
name (String) − the name of the parameter
value (Object) − the value of the parameter
<pre>
<ui:component>
<ui:param name = "key" value = "[0]"/>
<ui:param name = "value" value = "[1]"/>
<ui:param name = "context" value = "[2]"/>
</ui:component>
</pre>
The Property Tag
This property tag is used to get the property of a value, which will default to the top of the stack if none
is specified.
<s:push value = "myBean">
<!-- Example 1: -->
<s:property value = "myBeanProperty" />
<!-- Example 2: -->TextUtils
<s:property value = "myBeanProperty" default = "a default value" />
</s:push>
The Push Tag
These push tag is used to push value on stack for simplified usage.
<s:push value = "user">
<s:propery value = "firstName" />
<s:propery value = "lastName" />
</s:push>
The Set Tag
The set tag assigns a value to a variable in a specified scope. It is useful to assign a variable to a
complex expression and then simply reference that variable each time rather than the complex expression. The
scopes available are application, session, request, page and action.
<s:set name = "myenv" value = "[Link]"/>
<s:property value = "myenv"/>
The Text Tag
These text tag is used to render a I18n text message.
<!-- First Example -->
<s:i18n name = "[Link]">
<s:text name = "[Link]"/>
</s:i18n>
<!-- Second Example -->
<s:text name = "[Link]" />
Regulation 2023 Academic Year: 2025-2026
<!-- Third Examlpe -->
<s:text name = "[Link]">
<s:param >Mr Smith</s:param>
</s:text>
The URL Tag
These url tag is used to create a URL.
<-- Example 1 -->
<s:url value = "[Link]">
<s:param name = "id" value = "%{selected}" />
</s:url>
<-- Example 2 -->
<s:url action = "editGadget">
<s:param name = "id" value = "%{selected}" />
</s:url>
<-- Example 3-->
<s:url includeParams="get">
<s:param name = "id" value = "%{'22'}" />
</s:url>
Struts Form Tags
The list of form tags is a subset of Struts UI Tags. These tags help in the rendering of the user interface
required for the Struts web applications and can be categorized into three categories.
 Simple UI Tags
 Group UI Tags
 Select UI Tags
Simple UI tags
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<s:head/>
<title>Hello World</title>
</head>
<body>
<s:div>Email Form</s:div>
<s:text name = "Please fill in the form below:" />
<s:form action = "hello" method = "post" enctype = "multipart/form-data">
<s:hidden name = "secret" value = "abracadabra"/>
<s:textfield key = "[Link]" name = "from" />
<s:password key = "[Link]" name = "password" />
<s:textfield key = "[Link]" name = "to" />
<s:textfield key = "[Link]" name = "subject" />
<s:textarea key = "[Link]" name = "[Link]" />
<s:label for = "attachment" value = "Attachment"/>
<s:file name = "attachment" accept = "text/html,text/plain" />
<s:token />
<s:submit key = "submit" />
</s:form>
</body>
</html>
If aware of HTML, then all the tags used are very common HTML tags with an additional prefix s: along with
each tag and different attributes.
Regulation 2023 Academic Year: 2025-2026
Group UI Tags
The group UI tags are used to create radio button and the checkbox. A simple view page [Link]
with check box and radio button tags.
<%@ page contentType = "text/html; charset = UTF-8"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head>
<body>
<s:form action = "[Link]">
<s:radio label = "Gender" name = "gender" list="{'male','female'}" />
<s:checkboxlist label = "Hobbies" name = "hobbies"
list = "{'sports','tv','shopping'}" />
</s:form>
</body>
</html>
Select UI Tags
The following program shows the different variations of the Select Tag offered by Struts.
[Link] with select tags
<%@ page contentType = "text/html; charset = UTF-8"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head> <body>
<s:form action = "[Link]">
<s:select name = "username" label = "Username"
list = "{'Mike','John','Smith'}" />
<s:select label = "Company Office" name = "mySelection"
value = "%{'America'}" list="%{#{'America':'America'}}">
<s:optgroup label = "Asia"
list = "%{#{'India':'India','China':'China'}}" />
<s:optgroup label = "Europe"
list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" />
</s:select>
<s:combobox label = "My Sign" name = "mySign"
list = "#{'aries':'aries','capricorn':'capricorn'}" headerkey = "-1"
headervalue = "--- Please Select ---" emptyOption = "true" value = "capricorn" />
<s:doubleselect label = "Occupation" name = "occupation"
list = "{'Technical','Other'}" doublename = "occupations2"
doubleList="top == 'Technical' ?
{'I.T', 'Hardware'} : {'Accounting', 'H.R'}" />
</s:form>
</body>
</html>
Struts AJAX Tags
Struts use the DOJO framework for the AJAX tag implementation. For struts AJAX tags we need to add
[Link] to your classpath. It can be obtained this file from the lib folder of your struts2
download (C:\struts-2.2.3all\struts-2.2.3\lib\[Link])
Example
[Link] as follows
Regulation 2023 Academic Year: 2025-2026
<%@ page contentType = "text/html; charset = UTF-8"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<%@ taglib prefix = "sx" uri = "/struts-dojo-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
<sx:head />
</head>
<body>
<s:form>
<sx:autocompleter label = "Favourite Colour"
list = "{'red','green','blue'}" />
<br />
<sx:datetimepicker name = "deliverydate" label = "Delivery Date"
displayformat = "dd/MM/yyyy" />
<br />
<s:url id = "url" value = "/[Link]" />
<sx:div href="%{#url}" delay="2000">
Initial Content
</sx:div>
<br/>
<sx:tabbedpanel id = "tabContainer">
<sx:div label = "Tab 1">Tab 1</sx:div>
<sx:div label = "Tab 2">Tab 2</sx:div>
</sx:tabbedpanel>
</s:form> </body> </html>
4.3.3 Process of Struts Framework
 Request Handling: When a user sends a request, Struts uses a controller (usually
ActionServlet) to process it.
 Mapping: The request is mapped to an appropriate Action class as defined in the struts-
[Link] file.
 Action Execution: The Action class executes business logic, and based on the result, it returns
a forward to a JSP or another Action.
 View Rendering: The View (usually a JSP) renders the result to the user.
 Response: Finally, Struts sends the response back to the client browser.
This process ensures that the application has a clear separation of concerns, making it easy to manage,
extend, and test.

4.3.4 MVC Architecture for strut Environment


The Struts Framework is a standard for developing well-architected Web applications. It has the following
features:
 Open source
 Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three
levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
 Implements the JSP Model 2 Architecture
 Stores application routing information and request mapping in a single core file, struts-
[Link]
Regulation 2023 Academic Year: 2025-2026
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to
the developer.

Figure 4.3 MVC Architecture for strut Environment


All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration
file [Link] is used by the controller to determine the routing of the flow. This flows consists
of an alternation between two transitions:
From View to A user clicks on a link or submits a form on an HTML or JSP page. The
Action controller receives the request, looks up the mapping for this request, and
forwards it to an action. The action in turn calls a Model layer (Business layer)
service or function.
From Action to After the call to an underlying function or service returns to the action class, the
View action forwards to a resource in the View layer and a page is displayed in a web
browser.

The below sequence diagram describes the flow in more detail:

Figure 4.4 workflow of struts


1. User clicks on a link in an HTML page.
2. Servlet controller receives the request, looks up mapping information in [Link], and
routes to an action.
3. Action makes a call to a Model layer service.
4. Service makes a call to the Data layer (database) and the requested data is returned.
5. Service returns to the action.
6. Action forwards to a View resource (JSP page)
7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
8. JSP file is invoked and sent to the browser as HTML.
Regulation 2023 Academic Year: 2025-2026
9. User is presented with a new HTML page in a web browser.

4.4 Struts Environment


To prepare a development environment with struts, first we have to install JDK, Tomcat and
Eclipse in systems.
4.4.1 Setup Java Development Kit (JDK)
To download the latest version of SDK from Oracle's Java site − Java SE Downloads. Here will
find instructions for installing JDK in downloaded files, follow the given instructions to install and
configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the
directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If running Windows and installed the SDK in C:\jdk1.5.0_20, it should be inputting the following line
in your C:\[Link] file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP −
 Right-click on My Computer, Select Properties, then Advanced, then Environment Variables.
Then, you would update the PATH value and press the OK button.
 On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and use the C
shell, it would put the following into .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse,
IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows
where installed Java, otherwise do proper setup as per the given document of IDE.
4.4.2 Setup Apache Tomcat
To download the latest version of Tomcat from [Link] Once downloaded
the installation, unpack the binary distribution into a convenient location. For example in C:\apache-
tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on Linux/Unix and create
CATALINA_HOME environment variable pointing to these locations. To start tomcat by executing
the following commands on windows machine, or you can simply double click on [Link]
%CATALINA_HOME%\bin\[Link]
or
C:\apache-tomcat-6.0.33\bin\[Link]
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine
$CATALINA_HOME/bin/[Link]
or
/usr/local/apache-tomcat-6.0.33/bin/[Link]
After a successful startup, the default web applications included with tomcat will be available by
visiting [Link] If everything is fine, then it should display the following result
Regulation 2023 Academic Year: 2025-2026

Figure 4.5 Apache Tomcat Server


4.4.3 Setup Eclipse (IDE)
To install Eclipse Download the latest Eclipse binaries from
[Link] Once download the installation, unpack the binary distribution
into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix
and finally set PATH variable appropriately. Eclipse can be started by executing the following
commands on windows machine, or can simply double click on [Link]
%C:\eclipse\[Link]
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine, it should display the following result

Figure 4.6 Eclipse IDE


4.4.4 Setup Struts Libraries
Following are the simple steps to download and install Struts on the machine. Make a choice
whether want to install Struts on Windows, or Unix and then proceed to the next step to download .zip
file for windows and .tz file for Unix. Download the latest version of Struts binaries from
[Link] To download [Link] and when unzip the
downloaded file it will give directory structure inside C:\struts-2.2.3 as follows.
Regulation 2023 Academic Year: 2025-2026

Figure 4.7 Struts libaray files


Second step is to extract the zip file in any location, downloaded & extracted [Link]
in c:\ folder on my Windows 7 machine so that it will have all the jar files into C:\struts-2.2.3\lib. Set
CLASSPATH variable properly otherwise will face problem while running an application.
4.5 Handling Exceptions in Struts
Struts provide an easier way to handle uncaught exception and redirect users to a dedicated
error page. It can easily configure Struts to have different error pages for different exceptions. Strut
makes the exception handling easy by the use of the "exception" interceptor. The "exception"
interceptor is included as part of the default stack, so don't have to do anything extra to configure it. It
is available out-of-the-box ready for to use.
Let us see a simple Hello World example with some modification in [Link]
file. Here, deliberately introduced a NullPointer Exception in our HelloWorldAction action code.
package [Link].struts2;
import [Link];
public class HelloWorldAction extends ActionSupport{
private String name;
public String execute(){
String x = null;
x = [Link](0);
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
}
4.5.1 [Link] as follows
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
Regulation 2023 Academic Year: 2025-2026
Hello World, <s:property value = "name"/>
</body>
</html>
4.5.2 [Link]
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World From Struts2</h1>
<form action = "hello">
<label for = "name">Please enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Say Hello"/>
</form>
</body>
</html>
4.5.3 [Link]
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"[Link]
<struts>
<constant name = "[Link]" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "hello"
class = "[Link]"
method = "execute">
<result name = "success">/[Link]</result>
</action>
</package>
</struts>
Now right click on the project name and click Export > WAR File to create a War file. Then
deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access
URL [Link] This will produce the following screen as
Regulation 2023 Academic Year: 2025-2026

Figure 4.8 [Link]


Enter a value "Struts2" and submit the page. It should give the following page

Figure 4.9 Exception Interceptor


As shown in the above example, the default exception interceptor does a great job of handling
the exception. Let us now create a dedicated error page for our Exception. Create a file called [Link]
with the following contents.
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<title></title>
</head>
<body>
This is my custom error page
Regulation 2023 Academic Year: 2025-2026
</body>
</html>
Let us now configure Struts to use this this error page in case of an exception. Let us modify
the [Link] as follows,
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"[Link]
<struts>
<constant name = "[Link]" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "hello"
class = "[Link]"
method = "execute">
<exception-mapping exception = "[Link]"
result = "error" />
<result name = "success">/[Link]</result>
<result name = "error">/[Link]</result>
</action> </package> </struts>
As shown in the example above, now to configure struts to use the dedicated [Link] for the
NullPointerException. If rerun the program now, it will get the following output

Figure 4.10 [Link]


In addition to this, Struts2 framework comes with a "logging" interceptor to log the exceptions.
By enabling the logger to log the uncaught exceptions can easily look at the stack trace and work out
what went wrong.

4.5.4 Global Exception Mappings


Global exception mappings can set an exception globally which will apply to all the actions.
For example, to catch the same NullPointerException exceptions, it could add <global-exception-
mappings...> tag inside <package...> tag and its <result...> tag should be added inside the <action...>
tag in [Link] file as follows
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"[Link]
Regulation 2023 Academic Year: 2025-2026
<struts>
<constant name = "[Link]" value = "true" />
<package name = "helloworld" extends = "struts-default">
<global-exception-mappings>
<exception-mapping exception = "[Link]"
result = "error" />
</global-exception-mappings>
<action name = "hello"
class = "[Link]"
method = "execute">
<result name = "success">/[Link]</result>
<result name = "error">/[Link]</result>
</action>
</package>
</struts>
4.6 Validation and Development in Struts
Struts validation frameworks are used to assists the application to run the rules to perform
validation before the action method is executed. Client side validation is usually achieved using
Javascript. However, one should not rely upon client side validation alone. The best practices suggest
that the validation should be introduced at all levels of application framework.
There are two ways of adding validation to Struts project. Here, we will take an example of an
Employee whose name and age should be captured using a simple page, and will put these two
validations to make sure that the user always enters a name and age which should be in a range
between 28 and 65.
The main JSP page of the example as follows
4.6.1 Create Main Page
Main page JSP file [Link], which will be used to collect Employee related information
mentioned above.
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<title>Employee Form</title>
</head>
<body>
<s:form action = "empinfo" method = "post">
<s:textfield name = "name" label = "Name" size = "20" />
<s:textfield name = "age" label = "Age" size = "20" />
<s:submit name = "submit" label = "Submit" align="center" />
</s:form>
</body>
</html>
The [Link] makes use of Struts tag, which s:textfield tag prints a input field, and the s:submit prints
a submit button. Label property for each tag which creates label for each tag.
4.6.2 Create Views
Use JSP file [Link] which will be invoked in case defined action returns SUCCESS.
Regulation 2023 Academic Year: 2025-2026
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<title>Success</title>
</head>
<body>
Employee Information is captured successfully.
</body>
</html>
4.6.3 Create Action
To define a small action class Employee, and then add a method called validate() as shown
below in [Link] file. Make sure that action class extends the ActionSupport class, otherwise
validate method will not be executed.
package [Link].struts2;
import [Link];
public class Employee extends ActionSupport {
private String name;
private int age;
public String execute() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
public void validate() {
if (name == null || [Link]().equals("")) {
addFieldError("name","The name is required");
}
if (age < 28 || age > 65) {
addFieldError("age","Age must be in between 28 and 65");
} } }
As shown in the above example, the validation method checks whether the 'Name' field has a
value or not. If no value has been supplied add a field error for the 'Name' field with a custom error
message. Secondly, to check if entered value for 'Age' field is in between 28 and 65 or not, if this
condition does not meet add an error above the validated field.
4.6.4 Configuration Files
Regulation 2023 Academic Year: 2025-2026
Finally, let us put everything together using the [Link] configuration file as follows
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"[Link]
<struts>
<constant name = "[Link]" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "empinfo"
class = "[Link]"
method = "execute">
<result name = "input">/[Link]</result>
<result name = "success">/[Link]</result>
</action>
</package>
</struts>
Following is the content of [Link] file
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "[Link]
xmlns = "[Link]
xmlns:web = "[Link]
xsi:schemaLocation = "[Link]
[Link]
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
[Link]
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Right click on the project name and click Export > WAR File to create a War file. Then deploy this
WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL
[Link]
This will produce the following screen
Regulation 2023 Academic Year: 2025-2026

Figure 4.11 [Link]


Now do not enter any required information, just click on Submit button. You will see the
following result

Figure 4.12 [Link]


Enter the required information but enter a wrong From field, let us say name as "test" and age as 30,
and finally click on Submit button. It will give the following result
Regulation 2023 Academic Year: 2025-2026
Figure 4.13 [Link]

Validation in Struts
When the user presses the submit button, struts will automatically execute the validate method
and if any of the “if” statements listed inside the method are true, Struts will call its addFieldError
method. If any errors have been added, then Struts will not proceed to call the execute method. Rather
the Struts framework will return input as the result of calling the action. Hence, when validation fails
and Struts returns input, the Struts framework will redisplay the [Link] file. Since struts form tags,
struts will automatically add the error messages just above the form filed.
These error messages are the ones specified in the addFieldError method call. The
addFieldError method takes two arguments. The first, is the form field name to which the error applies
and the second, is the error message to display above that form field.
addFieldError("name","The name is required");
To handle the return value of input need to add the following result to our action node in [Link].
<result name = "input">/[Link]</result>
4.6.5 XML Based Validation
The second method of doing validation is by placing an xml file next to the action class. Struts
XML based validation provides more options of validation like email validation, integer range
validation, form validation field, expression validation, regex validation, required validation,
requiredstring validation, stringlength validation and etc.
The xml file needs to be named '[action-class]'-[Link]. So in our case create a file
called [Link] with the following contents
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"[Link]
<validators>
<field name = "name">
<field-validator type = "required">
<message>
The name is required.
</message>
</field-validator>
</field>
<field name = "age">
<field-validator type = "int">
<param name = "min">29</param>
<param name = "max">64</param>
<message>
Age must be in between 28 and 65
</message>
</field-validator>
</field>
</validators>
Above XML file would be kept in your CLASSPATH ideally along with class file. Let us have
our Employee action class as follows without having validate() method
package [Link].struts2;
import [Link];
public class Employee extends ActionSupport{
private String name;
Regulation 2023 Academic Year: 2025-2026
private int age;
public String execute() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
} }
The advantage of having an xml file to store the configuration allows the separation of the validation
from the application code.
4.7 Data Management and Database Integration
Struts is a MVC framework and not a database framework but it provides excellent support for
JPA/Hibernate database integration.
The first step is to setup and prime our database. MySQL as my database for this example.
MYSQL database has the default username "root" and "root123" password
CREATE TABLE `struts_tutorial`.`login` (
`user` VARCHAR( 10 ) NOT NULL ,
`password` VARCHAR( 10 ) NOT NULL ,
`name` VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( `user` )
) ENGINE = InnoDB;
INSERT INTO `struts_tutorial`.`login` (`user`, `password`, `name`)
VALUES ('scott', 'navy', 'Scott Burgemott');
Next step is to download the MySQL Connector jar file and placing this file in the WEB-
INF\lib folder of your project. After we have done this, we are now ready to create the action class.
4.7.1 Create Action
The action class has the properties corresponding to the columns in the database table. The
user, password and name as String attributes. In the action method use the user and password
parameters to check if the user exists, if so display the user name in the next screen. If the user has
entered wrong information send them to the login screen again.
Following is the content of [Link] file
package [Link].struts2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LoginAction extends ActionSupport {
private String user;
private String password;
private String name;
Regulation 2023 Academic Year: 2025-2026
public String execute() {
String ret = ERROR;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/struts_tutorial";
[Link]("[Link]");
conn = [Link](URL, "root", "root123");
String sql = "SELECT name FROM login WHERE";
sql+=" user = ? AND password = ?";
PreparedStatement ps = [Link](sql);
[Link](1, user);
[Link](2, password);
ResultSet rs = [Link]();
while ([Link]()) {
name = [Link](1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
[Link]();
} catch (Exception e) {
}
} }
return ret;
}
public String getUser() {
return user;
}

public void setUser(String user) {


[Link] = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
[Link] = password;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}}
4.7.2 Create Main Page
Now to create a JSP file [Link] to collect the username and password. This username and
Regulation 2023 Academic Year: 2025-2026
password will be checked against the database.
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "loginaction" method = "post">
User:<br/><input type = "text" name = "user"/><br/>
Password:<br/><input type = "password" name = "password"/><br/>
<input type = "submit" value = "Login"/>
</form>
</body>
</html>
4.7.3 Create Views
Let us create [Link] file which will be invoked in case action returns SUCCESS, but will
have another view file in case of an ERROR is returned from the action.
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Successful Login</title>
</head>
<body>
Hello World, <s:property value = "name"/>
</body>
</html>
Following will be the view file [Link] in case of an ERROR is returned from the action.
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Invalid User Name or Password</title>
</head>
<body>
Wrong user name or password provided.
</body>
</html>
4.7.4 Configuration Files
Finally, let us put everything together using the [Link] configuration file as follows
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"[Link]
<struts>
Regulation 2023 Academic Year: 2025-2026
<constant name = "[Link]" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "loginaction"
class = "[Link]"
method = "execute">
<result name = "success">/[Link]</result>
<result name = "error">/[Link]</result>
</action>
</package>
</struts>
Following is the content of [Link] file −
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "[Link]
xmlns = "[Link]
xmlns:web = "[Link]
xsi:schemaLocation = "[Link]
[Link]
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
[Link]
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Now, right click on the project name and click Export > WAR File to create a War file. Then
deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access
URL [Link] This will produce the following screen
Regulation 2023 Academic Year: 2025-2026

Figure 4.14 [Link]


Enter a wrong user name and password. It should give the next page.

Figure 4.15 [Link]


Now enter scott as user name and navy as password. It should give the next page.
Regulation 2023 Academic Year: 2025-2026

Figure 4.16 [Link]

You might also like