0% found this document useful (0 votes)
2 views50 pages

Advanced Java Practical File

The document is a practical file for an Advanced Java Laboratory course at Bhai Maha Singh College, detailing various experiments related to Java Servlets, JSP, and session tracking. It includes an index of experiments, explanations of HTTP requests and responses, cookies, and the lifecycle of JSP pages. The document also provides sample code for implementing servlets and cookies, along with their respective functionalities.

Uploaded by

sekhon85578
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)
2 views50 pages

Advanced Java Practical File

The document is a practical file for an Advanced Java Laboratory course at Bhai Maha Singh College, detailing various experiments related to Java Servlets, JSP, and session tracking. It includes an index of experiments, explanations of HTTP requests and responses, cookies, and the lifecycle of JSP pages. The document also provides sample code for implementing servlets and cookies, along with their respective functionalities.

Uploaded by

sekhon85578
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

Advanced Java Laboratory

(PGCA1922)

PRACTICAL FILE

MCA (IYEAR–2nd SEM)

BHAI MAHA SINGH COLLEGE OF


INFORMATION TECHNOLOGY &
Bhai Maha Singh College of Engineering
LIFE SCIENCES
SHRI MUKTSAR SAHIB

Submitted by:- Submitted to:-


Name: - Mr. Dilpreet Singh
Rollno:- Assistant Professor
Branch/Sec:- MCA 2nd Sem.

1
Advanced Java Lab Index

[Link] Name of the Experiment PageNo Date Signature

1 Create a Servlet to handle HTTP Requests 3-7


and Responses.

2 Implementation of the concept of Cookies and 8-13


Session Tracking.

3 Illustrate the concept of JavaServer 14-16


Pages (JSP).
4 Create a JavaBean by using Bean Developer Kit 17-18
(BDK).

5 Implementation of various types of beans like 19-21


Session Bean and Entity Bean
6 Introduction to Struts platform with basic 22-26
connectivity

7 Deploying first sample program 27-41


using MVC architecture in struts

8 Implementing database connectivity in struts. 42-45

9 Take a web site and prepare the SEO report of the 46-47
website including status of following factors: Title
tag, meta-description tag, header tags, keyword
consistency, number of back links, [Link] and
xml sitemaps then after going through the steps of
SEO prepare the report
10 Discuss any five tools to prepare the list of ten 48-50
organic key words for SEO purpose.

2
1. Create a Servlet to handle HTTP Requests and Responses

HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting information;
it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which includes following
information:

o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header

The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in
uppercase.

The HTTP request methods are: 10sPla

3
HTTP Description
Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra info sent with
the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond

Servlet – Response

A web application is built using Servlet technology (resides at the server-side and generates a
dynamic web page). Because of the Java programming language, servlet technology is dependable
and scalable. CGI (Common Gateway Interface) scripting language was widely used as a server-side
programming language prior to Servlet.

Servlet – Response

A servlet can use this object to help it provide a response to the client. A ServletResponse object is
created by the servlet container and passed as an argument to the servlet’s service function.

Use the ServletOutputStream supplied by getOutputStream to deliver binary data in a MIME body
response (). Use the PrintWriter object given by getWriter to deliver character data (). Use a

4
ServletOutputStream and manually control the character sections to blend binary and text data, for
example, to generate a multipart response.
The setCharacterEncoding([Link]) and setContentType([Link]) methods can be
used to provide the charset for the MIME body response, or the setLocale([Link]) method
can be used to specify it implicitly. Implicit requirements are overridden by explicit specifications.
ISO-8859-1 will be used if no charset is supplied. For the character encoding to be utilized, the
setCharacterEncoding, setContentType, or setLocale methods must be called before getWriter and
before committing the response.
Some Important Methods of ServletResponse
Methods Description

It returns the name of the MIME charset that was used in the
String getCharacterEncoding()
body of the client response.

String getContentType() It returns the response content type. e.g. text, HTML etc.

ServletOutputStream This method returns a ServletOutputStream that may be used to


getOutputStream() write binary data to the response.

The PrintWriter object is used to transmit character text to the


PrintWriter getWriter()
client.

Sets the length of the response’s content body. This function


void setContentLength(int len)
sets the HTTP Content-Length header in HTTP servlets.

void setContentType(String
Sets the type of the response data.
type)

void setBufferSize(int size) specifies the recommended buffer size for the response’s body.

int getBufferSize() Returns the buffer size

5
Implementation: The setContentType() and getWriter() methods of the ServletResponse interface
were utilised in the example below.

A. File: [Link]
 HTML

<html> <body> <title> GEEKSFORGEEKS </title>

<form action="GFG" method="get"> Enter your username: <br><br>

<input type="text" name="uname"> <br><br>

<input type="submit" value="login">

</form>

</body></html>

B. Application File ([Link])


 Java

import [Link].*;

import [Link].*;

import [Link].*;

public class GFG extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

[Link]("text/html");PrintWriter pwriter=[Link]();

String name=[Link]("uname"); [Link]("This is user details


page:"); [Link]("Hello "+name); [Link]();

} }

6
C. [Link]
 XML

<web-app>

<servlet> <servlet-name>GFG</servlet-name> <servlet-class>GFG</servlet-class>

</servlet>

<servlet-mapping> <servlet-name>GFG</servlet-name> <url-pattern>/GFG</url-


pattern>

</servlet-mapping>

</web-app>

Output:
First Screen shows the following output:

Second Screen shows the following output:

7
2. Implementation of the concept of Cookies and Session
Tracking
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by
the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

8
Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed
only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class
[Link] class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Constructor of Cookie class


Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

9
public String getName() Returns the name of the cookie. The name cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They
are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in


response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
from the browser.

How to create Cookie?


Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. [Link](ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. [Link](0);//changing the maximum age to 0 seconds
3. [Link](ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

10
1. Cookie ck[]=[Link]();
2. for(int i=0;i<[Link];i++){
3. [Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from too many
browsers with different values, you will get the different value.

[Link]
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

[Link]
1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class FirstServlet extends HttpServlet {
5. public void doPost(HttpServletRequest request, HttpServletResponse response){
6. try{
7. [Link]("text/html");
8. PrintWriter out = [Link]();
9. String n=[Link]("userName");
10. [Link]("Welcome "+n);
11. Cookie ck=new Cookie("uname",n);//creating cookie object

11
12. [Link](ck);//adding cookie in the response
13. //creating submit button
14. [Link]("<form action='servlet2'>");
15. [Link]("<input type='submit' value='go'>");
16. [Link]("</form>");
17. [Link]();
18. }catch(Exception e){[Link](e);}
19. }
20. }

[Link]
1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5. public class SecondServlet extends HttpServlet {
6. public void doPost(HttpServletRequest request, HttpServletResponse response){
7. try{
8. [Link]("text/html");
9. PrintWriter out = [Link]();
10. Cookie ck[]=[Link]();
11. [Link]("Hello "+ck[0].getValue());
12. [Link]();
13. }catch(Exception e){[Link](e);}
14. }
15. }

[Link]
1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>s2</servlet-name>
12. <servlet-class>SecondServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>

12
15. <servlet-name>s2</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping>
18. </web-app>
19.
20. Output

13
3. Illustrate the concept of JavaServer Pages (JSP).
JSP technology is used to create web application just like Servlet technology. It can be thought of as an
extension to Servlet because it provides more functionality than servlet such as expression language, JSTL,
etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because
we can separate designing and development. It provides some additional features such as Expression
Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP. In
addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP,
that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic. In
Servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs to
be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover,
we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).

14
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The JSP
translator is a part of the web server which is responsible for translating the JSP page into Servlet. After
that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the
processes that happen in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We have
saved this file as [Link]. Put it in a folder and paste the folder in the web-apps directory in apache
tomcat to run the JSP page.

[Link]

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP page.
We will learn scriptlet tag later.

1. <html>
2. <body>

15
3. <% [Link](2*5); %>
4. </body>
5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL [Link] for example,
[Link]

Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For example, put JSP
files in a folder directly and deploy that folder. It will be running fine. However, if you are using Bean class,
Servlet or TLD file, the directory structure is required.

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF
folder or in any directory.

16
4. Create a JavaBean by using Bean Developer Kit (BDK).
Visual Programming Languages (such as Visual Basic and Delphi) have been very popular in building GUI applications.
In visual programming, you can drag and drop a visual component into a Application Builder and attach event
handler to the component. Visual programming is ideal for rapid prototyping of GUI applications. Visual programming
relies on component and event-driven technology. Components are reusable software units that can be assembled
into an application via an application building tool (e.g., Visual Studio, JBuilder, NetBeans, Eclipse).

In Java, visual programming is supported via the "Javabean" API. The application builder tool loads the beans into a
"toolbox" or "palette". You can select a bean from the toolbox, drop it into a "form", modify its appearance or
properties, and define its interaction with other beans. Using the JavaBeans component technology, you can compose
(or assemble) an application with just a few lines of codes.
"A Javabean is a reusable software component that can be manipulated visually in an application builder tool."
"A Javabean is an independent, reusable software component. Beans may be visual object, like Swing components
(e.g. JButton, JTextField) that you can drag and drop using a GUI builder tool to assemble your GUI application.
Beans may also be invisible object, like queues or stacks. Again, you can use these components to assemble your
application using a builder tool."

Javabeans expose their features (such as properties, methods, events) to the application builder tools for visual
manipulation. These feature names must adhere to a strict naming convention in order for them to be examined
automatically. In other words, an application builder tool relies on these naming conventions to discover the exposed
features, in a process known as introspection. For examples,

1. A property called propertyName of type PropertyType has the following convention:


2. PropertyType propertyName // declaration
3. public PropertyType getPropertyName() // getter
4. public void setPropertyName(PropertyType p) // setter
5. For an event source object, which can fire an event called XxxEvent specified in an interface XxxListener,
the following methods must be provided to register and remove listener:
6. public void addXxxListener(XxxListener l)
7. public void removeXxxListener(XxxListener l)

I assume that you are familiar with OOP concepts (such as interface, polymorphism) and GUI programming (in AWT
and Swing). Otherwise, study the earlier chapters.

JavaBean Development Software


Bean Development Kit (BDK)
NOTE: BDK is no longer available for download from the Java website.

Bean Development Kit (BDK) is a tool for testing whether your Javabeans meets the JavaBean specification. Follow the
instruction provided to install the BDK. Read the documentation and tutorial provided (in particular, "The Java
Tutorial, specialized trial on JavaBeans"). BDK comes with a set of sample demo beans. You should try them out and
closely study these demo beans before writing our own beans.

Let's try to assemble (or compose) an application using the BDK demo beans.
1. Start the "beanbox" by running "$bdk\beanbox\[Link]".
2. From the "Toolbox" window, select "Juggler" (a demo bean) and place it inside the "beanbox" (by clicking the
desired location in the "beanbox" window). Observe the "Property" window of the Juggler bean.

17
3. Create a button by selecting "OurButton" demo bean from the "Toolbox" and place it inside the "Beanbox". In
the "Property" window, change the "label" from "press" to "start".
4. Focus on "OurButton", choose "Edit”" from menu ⇒ "Events" ⇒ "mouse" ⇒ "mouseClicked" and place it onto
the "Juggler" (i.e., "Juggler" is the target of this event). In the "EventTargetDialog", select method
"startJuggling" as the event handler.
5. Create another button by selecting "OurButton" bean from "Toolbox" and place it inside the "Beanbox" again.
In the "Property" window, change the "label" from "press" to "stop".
6. Focus on the stop button, choose "Edit" from menu ⇒ "Events" ⇒ "mouse" ⇒ "mouseClicked" and place it
onto the "Juggler". In the "EventTargetDialog", select method "stopJuggling" as the event handler.
7. Click on the buttons, and observe the result.

[TODO] BDK diagram

It is easy to assemble an application from components. You can do it without writing a single line code, if these
components are readily available.

NOTES:
 BDK is old (since JDK 1.1), and does not make use of many of the latest Java features. For example, it uses AWT
GUI classes rather than the Swing.
 To run BDK under JDK 1.5 and above, you may have to recompile the program.
Bean Builder
Bean Builder can be downloaded from [Link]

[TODO]
NetBeans
[TODO]

Writing Your Own Javabeans


The JavaBeans APIs covers five aspects:
1. Properties: represent the attributes of a component.
2. Event Handling: allows beans to communicate with each others (JavaBean uses JDK 1.1 AWT event-delegation
model).
3. Persistence: allows beans' internal states to be stored and later restored.
4. Introspection: allows Application Builder tool to analyze beans.
5. Application Builder Tool: for composing applications from Javabeans components.

18
5. Implementation of various types of beans like Session Bean
and Entity Bean.
What Is a Session Bean?

A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client
invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing
business tasks inside the server.

As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the
same way that an interactive session can have only one user. Like an interactive session, a session bean is not persistent. (That is, its data
is not saved to a database.) When the client terminates, its session bean appears to terminate and is no longer associated wi th the client.

For code samples, see Chapter 22, Session Bean Examples.

State Management Modes


There are two types of session beans: stateful and stateless.

Stateful Session Beans


The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of
a unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.

The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state
disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean
ends there is no need to retain the state.

Stateless Session Beans


A stateless session bean does not maintain a conversational state with the client. W hen a client invokes the methods of a stateless bean,
the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. When the method is
finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless
beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a
stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean
should apply accross all clients.

Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of
clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same num ber of clients.

A stateless session bean can implement a web service, but other types of enterprise beans cannot.

When to Use Session Beans


In general, you should use a session bean if the following circumstances hold:

 At any given time, only one client has access to the bean instance.
 The state of the bean is not persistent, existing only for a short period (perhaps a few hours).
 The bean implements a web service.

Stateful session beans are appropriate if any of the following conditions are true:

 The bean’s state represents the interaction between the bean and a specific client.
 The bean needs to hold information about the client across method invocations.
 The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
 Behind the scenes, the bean manages the work flow of several enterprise beans. For an example, see
the AccountControllerBean session bean in Chapter 37, The Duke's Bank Application.

To improve performance, you might choose a stateless session bean if it has any of these traits:

19
 The bean’s state has no data for a specific client.
 In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to
send an email that confirms an online order.

Enterprise Java Beans (EJB)



Note
[Link]: This package has been deprecated in Java 9 and later
versions, in favor of
using annotations and other modern ways of creating beans.
Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of enterprise
software. EJB is a server-side software element that summarizes business logic of an application.
Enterprise Java Beans web repository yields a runtime domain for web related software elements
including computer reliability, Java Servlet Lifecycle (JSL) management, transaction procedure and
other web services. The EJB enumeration is a subset of the Java EE enumeration.
The EJB enumeration was originally developed by IBM in 1997 and later adopted by Sun
Microsystems in 1999 and enhanced under the Java Community Process.
The EJB enumeration aims to provide a standard way to implement the server-side business software
typically found in enterprise applications. Such machine code addresses the same types of problems,
and solutions to these problems are often repeatedly re-implemented by programmers. Enterprise
Java Beans is assumed to manage such common concerns as endurance, transactional probity and
security in a standard way that leaves programmers free to focus on the particular parts of the
enterprise software at hand.
To run EJB application we need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
1. Life cycle management
2. Security
3. Transaction management
4. Object pooling

Types of Enterprise Java Beans


There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by local, remote or
webservice client. There are two types of session beans: (i) Stateful session bean and (ii) Stateless
session bean.

 (i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful session bean can be
used to access various method calls by storing the information in an instance variable. Some of
the applications require information to be stored across separate method calls. In a shopping site,
the items chosen by a customer must be stored as data is an example of stateful session bean.

 (ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent storage mechanism,
such as a state or database and can used shared data. Stateless session bean can be used in

20
situations where information is not required to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by
passing message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated. Now, it
is replaced with JPA (Java Persistent API). There are two types of entity bean:

 (i) Bean Managed Persistence :


In a bean managed persistence type of entity bean, the programmer has to write the code for
database calls. It persists across multiple sessions and multiple clients.

 (ii) Container Managed Persistence :


Container managed persistence are enterprise bean that persists across database. In container
managed persistence the container take care of database calls.

When to use Enterprise Java Beans


[Link] needs Remote Access. In other words, it is distributed.
[Link] needs to be scalable. EJB applications supports load balancing, clustering and fail-
over.
[Link] needs encapsulated business logic. EJB application is differentiated from
demonstration and persistent layer.

Advantages of Enterprise Java Beans


1. EJB repository yields system-level services to enterprise beans, the bean developer can focus on
solving business problems. Rather than the bean developer, the EJB repository is responsible for
system-level services such as transaction management and security authorization.
2. The beans rather than the clients contain the application’s business logic, the client developer can
focus on the presentation of the client. The client developer does not have to code the pattern that
execute business rules or access databases. Due to this the clients are thinner which is a benefit that is
particularly important for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application assembler can build new applications
from the beans that already exists.

Disadvantages of Enterprise Java Beans


1. Requires application server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applications.

21
6. Introduction to Struts platform with basic connectivity.
Struts was the initial implementation of MVC design pattern and it has evolved a lot along with latest
enhancements in Java, Java EE technologies. Struts tutorial article is aimed to provide basic details of
Struts 2 and how we can create our first “Hello World” Struts 2 application.

Struts 2 Architecture Diagram


Below diagram shows different component of Struts 2 in a web application.

Struts 2 Hello World application. First of all we need is Struts 2 jar files, the easiest way is to download it
from Struts 2 Official Downloads page. But when you will check out the libs in the downloaded archive,
you will see a lot of jar files that we don’t need for our simple application. So I will create a maven
project and add struts-core dependency only, all the other transitive dependency jars will be
automatically downloaded and added to the application. Our final project
structure will be like below image.

Create a new Dynamic Web Project Struts2XMLHelloWorld in Eclipse and then convert it to maven
project like below image.

22
You will notice [Link] file is added in the root directory of the project. Our project setup in Eclipse is
ready, let’s look at the different components in order.
[Link]

Open [Link] file and add struts core dependency, the final [Link] will look like below.

<project xmlns=[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>Struts2XMLHelloWorld</groupId>
<artifactId>Struts2XMLHelloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>struts2-core</artifactId>
<version>[Link]</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration><source>1.6</source><target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId><version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>

<failOnMissingWebXml>false</failOnMissingWebXml></configuration>
</plugin>plugins>
<finalName>${[Link]}</finalName>

23
</build>
</project>
Notice that I have overridden finalName element to avoid version number getting added in the WAR file
when we do maven build. Other parts are added by Eclipse itself, the only dependency we need is
struts2-core whose current version is [Link] (as of 10-Sep-2013).

Struts 2 [Link] configuration


We need to add [Link] filter
to the web application and provide the URL pattern where we want Struts to take care of the client
request. Our [Link] looks like below;

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.0">
<display-name>Struts2XMLHelloWorld</display-name>

<filter>
<filter-name>struts2</filter-name>
<filter-
class>[Link]
r</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

For Struts 2 version below 2.1.3, the filter-class


was [Link].

Struts Tutorial - Result Pages


We have three JSP pages that will be used by the application, we are using Struts 2 tags to create our
JSP pages. [Link]
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login">
<s:textfield name="name" label="User Name"></s:textfield>

24
<s:textfield name="pwd" label="Password"
type="password"></s:textfield>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

Notice the form field names are name and pwd, we will see how they are used in Action
classes. [Link]
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="name"></s:property></h3>
</body>
</html>
Notice the struts tag s:property that we can use to get request attributes, the name is same as in
[Link]. [Link]
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Error Page</title>
</head>
<body>
<h4>User Name or Password is wrong</h4>
<s:include value="[Link]"></s:include>
</body>
</html>

This is a simple JSP page where we are adding error message and including login page in response.

Struts Tutorial - Action Classes


Our application has only one Action class where we are implementing Struts 2 Action
interface. [Link]
package [Link];
import [Link];
public class LoginAction implements Action {
@Override
public String execute() throws Exception {
if("pankaj".equals(getName()) && "admin".equals(getPwd()))
return "SUCCESS";

25
else return "ERROR";
}
//Java Bean to hold the form parameters
private String name;
private String pwd;
public String getName() {
return name; }
public void setName(String name) {
[Link] = name; }
public String getPwd() {
return pwd; }
public void setPwd(String pwd) {
[Link] = pwd; }

Notice the action class is also a java bean with same variables as [Link] and their getter and setter
methods. Struts will take care of mapping the request parameters to the action class variables.

Struts Tutorial - Configuration File


Since we are using XML based configuration for wiring our application, we need to create Struts
configuration file that should be named as [Link] and inside WEB-
INF/classes directory. [Link]

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"[Link]
<struts>
<package name="user" namespace="/User" extends="struts-default">
<action name="home"><result>/[Link]</result>action>
<action name="login" class="[Link]">
<result name="SUCCESS">/[Link]</result>result
name="ERROR">/[Link]</result></action>
</package>
</struts>

Struts Tutorial - Struts 2 Hello World Test

When we run our application, we get following response pages.

26
7. Deploying first sample program using MVC architecture in
struts
When you use Struts, the framework provides you with a controller servlet, ActionServlet, which is
defined in the Struts libraries that are included in the IDE, and which is automatically registered in
the [Link] deployment descriptor as shown below. The controller servlet uses a struts-
[Link] file to map incoming requests to Struts Action objects, and instantiate
any ActionForm objects associated with the action to temporarily store form data. The Action object
processes requests using its execute method, while making use of any data stored in the form bean.
Once the Action object processes a request, it stores any new data (i.e., in the form bean, or in a
separate result bean), and forwards the results to the appropriate view.

Setting Up a Struts Application


In the IDE, a Struts application is nothing more than a normal web application accompanied by the Struts
libraries and configuration files. You create a Struts application in the same way as you create any other
web application in the IDE - using the New Web Application wizard, with the additional step of indicating
that you want the Struts libraries and configuration files to be included in your application.

1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Java
Web in the list of Categories and then select Web Application in the list of Projects. Click Next.
2. In the Name and Location panel, enter MyStrutsApp for Project Name and click Next.
3. In the Server and Settings panel, select the server to which you want to deploy your application.
Only servers that are registered with the IDE are listed. (To register a server, click Add next to the
Server drop-down list.) Also, note that the Context Path to your deployed application
becomes /MyStrutsApp. Click Next.
4. Select Struts in the Frameworks panel.

27
Figure 3. Struts option displays in Frameworks panel of New Web Application wizard

<servlet>

<servlet-name>action</servlet-name>

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

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/[Link]</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>2</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

28
Creating JSP Pages
Begin by creating two JSP pages for the application. The first displays a form. The second is the view
returned when login is successful.

 Creating a Login Page


 Creating a Success Page

Creating a Login Page


1. Right-click the MyStrutsApp project node, choose New > JSP, and name the new file login.
Click Finish. The [Link] file opens in the Source Editor.
2. In the Source Editor, change the content of both the <title> and <h1> tags (or <h2> tags,
depending on the IDE version you are using) to Login Form.
3. Add the following two taglib directives to the top of the file:
<%@ taglib uri="[Link] prefix="bean" %>

<%@ taglib uri="[Link] prefix="html" %>

Figure 5. Code completion and Javadoc are supplied for Struts tags

The bean taglib provides you with numerous tags that are helpful when associating a form bean (i.e.,
an ActionForm bean) with the data collected from the form. The html taglib offers an interface between
the view and other components necessary to a web application. For example, below you replace common
html form tags with Struts' <html:form> tags. One benefit this provides is that it causes the server to
locate or create a bean object that corresponds to the value provided for html:form’s
`action element.

29
1. Below the <h1> (or <h2>) tags, add the following:

<html:form action="/login">

<html:submit value="Login" />

</html:form>

Whenever you finish typing in the Source Editor, you can tidy up the code by right-clicking and choosing
Format (Alt-Shift-F).

1. In the Palette (Window > Palette) in the right region of the IDE, drag a Table item from the HTML
category to a point just above the <html:submit value="Login" /> line. The Insert Table
dialog box displays. Set the rows to 3, columns to 2, and leave all other settings at 0. Later in the
tutorial, you will attach a stylesheet to affect the table display.

Figure 6. The Palette provides dialogs for easy-to-use code templates

Click OK, then optionally reformat the code (Alt-Shift-F). The form in [Link] now looks as follows:

<html:form action="/login">

<table border="0">

<thead>

<tr><th></th><th></th></tr>

</thead>

<tbody>

<tr><td></td><td></td></tr>

<tr><td></td><td></td></tr>

<tr><td></td><td></td></tr>

</tbody>

30
</table>

<html:submit value="Login" />

</html:form>

*Note: *You can safely delete the <thead> table row, as it is not used in this tutorial.

1. In the first table row, enter the following (changes in bold):

<tr>

<td>*Enter your name:*</td>

<td>*<html:text property="name" />*</td>

</tr>

1. In the second table row, enter the following (changes in bold):


<tr>

<td>*Enter your email:*</td>

<td>*<html:text property="email" />*</td></tr>

The html:text element enables you to match the input fields from the form with properties in the form
bean that will be created in the next step. So for example, the value of property must match a field
declared in the form bean associated with this form.

1. Move the <html:submit value="Login" /> element into the second column of the third table row, so
that the third table row appears as follows (changes in bold):
<tr>

<td></td>

<td>*<html:submit value="Login" />*</td>

</tr>

At this stage, your login form should look as follows:

<html:form action="/login">

<table border="0">

<tbody>

<tr><td>Enter your name:</td><td><html:text property="name" /></td></tr>

<tr><td>Enter your email:</td><td><html:text property="email" /></td></tr>

<tr><td></td><td><html:submit value="Login" /></td></tr>

31
</tbody>

</table>

</html:form>

Creating a Success Page


1. Right-click the MyStrutsApp project node, choose New > JSP, and name the new file success.
In the Folder field, click the adjacent Browse button and select WEB-INF from the dialog that
displays. Click Select Folder to enter WEB-INF in the Folder field. Any files contained in the WEB-
INF folder are not directly accessible to client requests. In order for [Link] to be properly
displayed, it must contain processed data. Click Finish.
2. In the Source Editor, change the content of the newly created page to the following:
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Login Success</title>

</head>

<body>

<h1>Congratulations!</h1>

<p>You have successfully logged in.</p>

<p>Your name is: .</p>

<p>Your email address is: .</p>

</body>

1. Add a bean taglib directive to the top of the file:


<%@ taglib uri="[Link] prefix="bean" %>

1. Add the following <bean:write> tags (changes in bold):

<p>Your name is: *<bean:write name="LoginForm" property="name" />*.</p>

<p>Your email address is: *<bean:write name="LoginForm" property="email" />*.</p>

By employing the <bean:write> tags, you make use of the bean taglib to locate the ActionForm bean
you are about to create, and display the user data saved for name and email.

Creating an ActionForm Bean


A Struts ActionForm bean is used to persist data between requests. For example, if a user submits a
form, the data is temporarily stored in the form bean so that it can either be redisplayed in the form page
(if the data is in an invalid format or if login fails) or displayed in a login success page (if data passes
validation).

32
1. Right-click the MyStrutsApp project node and choose New > Other. Under Categories choose
Struts, then under File Types choose Struts ActionForm Bean. Click Next.
2. Type in LoginForm for the Class Name. Then select [Link] in the Package drop-
down list and click Finish.

The IDE creates the LoginForm bean and opens it in the Source Editor. By default, the IDE provides it
with a String called name and an int called number. Both fields have accessor methods defined for
them. Also, the IDE adds a bean declaration to the [Link] file. If you open the struts-
[Link] file in the Source Editor, you can see the following declaration, which was added by the
wizard:

<form-beans>

*<form-bean name="LoginForm" type="[Link]" />*

</form-beans>

The IDE provides navigation support in the [Link] file. Hold down the Ctrl key and hover
your mouse over the LoginForm bean’s fully qualified class name. The name becomes a link, enabling
you to navigate directly to the class in the Source Editor:

Figure 7. Navigation support is provided in [Link]

1. In the LoginForm bean in the Source Editor, create fields and accompanying accessor methods
that correspond to the name and email text input fields that you created in [Link].
Because name has already been created in the LoginForm skeleton, you only need to
implement email.

Add the following declaration beneath name (changes in bold):

private String name;

*private String email;*

To create accessor methods, place your cursor on email and press Alt-Insert.

33
Figure 8. Insert Code menu displays when pressing Ctrl-I in Source Editor

Select Getter and Setter, then in the dialog that displays, select email : String and click Generate.
Accessor methods are generated for the email field.

*Note: *You can delete the declaration and accessor methods for number, as it is not used in this tutorial.

Creating an Action Class


The Action class contains the business logic in the application. When form data is received, it is
the execute method of an Action object that processes the data and determines which view to forward
the processed data to. Because the Action class is integral to the Struts framework, NetBeans IDE
provides you with a wizard.

1. In the Projects window, right-click the MyStrutsApp project node and choose New > Other. From
the Struts category choose Struts Action and click Next.
2. In the Name and Location panel, change the name to LoginAction.
3. Select [Link] in the Package drop-down list.
4. Type /login in Action Path. This value must match the value you set for the action attribute of
the <html:form> tags in [Link]. Make sure settings appear as in the screenshot below,
then click Next.

34
Figure 9. New Struts Action wizard

1. In the third step of the wizard, you are given the opportunity to associate the Action class with a
form bean. Notice that the LoginForm bean you previously created is listed as an option for
ActionForm Bean Name. Make the following adjustments to the panel:
 Delete the forward slash for the Input Resource field
 Set Scope to Request (Session is the default scope setting in Struts.)
 Deselect the Validate ActionForm Bean option Click Finish. The LoginAction class is
generated, and the file opens in the Source Editor. Also note that the
following action entry is added to the [Link] file:

<action-mappings>

*<action name="LoginForm" path="/login" scope="request"


type="[Link]" validate="false"/>*

<action path="/Welcome" forward="/[Link]"/>

</action-mappings>

Implementing Validation
In the Source Editor, browse through the LoginAction class and look at the execute method:

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

return [Link](SUCCESS);

Notice the definition of SUCCESS, listed beneath the LoginAction class declaration:

private final static String SUCCESS = "success";

Currently, the [Link] method is set to unconditionally forward any request to an output
view called success. This is not really desirable; you want to first perform some sort of validation on the
incoming data to determine whether to send the success view, or any different view.

 Accessing Bean Data and Preparing a Forwarding Condition


 Setting Up an Error Message

Accessing Bean Data and Preparing a Forwarding Condition


1. Type in the following code within the body of the execute method:

35
// extract user data

LoginForm formBean = (LoginForm)form;

String name = [Link]();

String email = [Link]();

In order to use the incoming form data, you need to take execute’s `ActionForm argument and cast it
as LoginForm, then apply the getter methods that you created earlier.

1. Type in the following conditional clause to perform validation on the incoming data:
// perform validation

if ((name == null) || // name parameter does not exist

email == null || // email parameter does not exist

[Link]("") || // name parameter is empty

[Link]("@") == -1) { // email lacks '@'

return [Link](FAILURE);

At this stage, the execute method should look as follows:

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

// extract user data

LoginForm formBean = (LoginForm) form;

String name = [Link]();

String email = [Link]();

// perform validation

if ((name == null) || // name parameter does not exist

email == null || // email parameter does not exist

[Link]("") || // name parameter is empty

[Link]("@") == -1) { // email lacks '@'

return [Link](FAILURE); }

36
return [Link](SUCCESS); }

1. Add a declaration for FAILURE to the LoginAction class (changes in bold):

private final static String SUCCESS = "success";

*private final static String FAILURE = "failure";*

Setting Up an Error Message

If the login form is returned, it would be good to inform the user that validation failed. You can accomplish
this by adding an error field in the form bean, and an appropriate <bean:write> tag to the form
in [Link]. Finally, in the Action object, set the error message to be displayed in the event that
the failure view is chosen.

1. Open LoginForm and add an error field to the class:

// error message

private String error;

1. Add a getter method and a setter method for error, as demonstrated above.
2. Modify the setter method so that it appears as follows:
public void setError() { [Link] ="<span style='color:red'>Please provide valid
entries for both fields</span>"; }

1. Open [Link] and make the following changes:

<html:form action="/login">

<table border="0">

<tbody>

*<tr><td colspan="2"><bean:write name="LoginForm" property="error"


filter="false"/>&amp;nbsp;</td></tr>*<tr>

<td>Enter your name:</td><td><html:text property="name" /></td></tr>

1. In LoginAction, within the if conditional clause, add a statement to set the error message
before forwarding the failure condition (changes in bold):

if ((name == null) || // name parameter does not exist

email == null || // email parameter does not exist

[Link]("") || // name parameter is empty

[Link]("@") == -1) { // email lacks '@'

*[Link]();*

return [Link](FAILURE);

37
}

Your completed LoginAction class should now appear as follows:

public class LoginAction extends [Link] {

private final static String SUCCESS = "success";

private final static String FAILURE = "failure";

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

// extract user data

LoginForm formBean = (LoginForm)form;

String name = [Link]();

String email = [Link]();

if ((name == null) || email == null || [Link]("") || [Link]("@")


== -1) { // email lacks '@'

[Link]();

return [Link](FAILURE);

return [Link](SUCCESS);

Adding forward Entries to [Link]

In order for the application to match JSP pages with forwarding conditions returned by LoginAction’s
`execute method, you need to add forward entries to the [Link] file.

1. Open [Link] in the Source Editor, right-click anywhere in the action entry
for LoginForm, and choose Struts > Add Forward.

38
Figure 10. Right-click and choose Struts > Add Forward

1. In the Add Forward dialog box, type success in Forward Name. Enter the path
to [Link] in the Resource File field (i.e., /WEB-INF/[Link]). The dialog box should
now look as follows:

Figure 11. Add Forward dialog creates a forward entry in [Link]

Click Add. Note that the following forward entry was added to [Link] (changes in bold):

<action name="LoginForm" path="/login" scope="request"


type="[Link]" validate="false">

*<forward name="success" path="/WEB-INF/[Link]"/>*

</action>

1. Perform the same action to add a forward entry for failure. Set the Resource File path
to /[Link]. The following forward entry is added to [Link] (changes
in bold):
<forward name="success" path="/WEB-INF/[Link]"/>

*<forward name="failure" path="/[Link]"/>*

Configuring and Running the Application


39
The IDE uses an Ant build script to build and run your web application. The IDE generated the build script
when you created the project, basing it on the options you entered in the New Project wizard. Before you
build and run the application, you need to set the application’s default entry point to [Link].
Optionally, you can also add a simple stylesheet to the project.

 Setting the Welcome Page


 Attaching a Stylesheet
 Running the Application

Setting the Welcome Page


1. In the Projects window, double-click the [Link] deployment descriptor. The tabs listed along
the top of the Source Editor provide you with an interface to the [Link] file. Click on the Pages
tab. In the Welcome Files field, enter [Link].

Figure 12. Graphical editor for the application’s deployment descriptor

Now click on the Source tab to view the file. Note that [Link] is now listed in the welcome-
file entry:

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

Attaching a Stylesheet
1. Add a simple stylesheet to the project. One easy way to do this is by saving this sample
stylesheet to your computer. Copy the file (Ctrl-C), then in the IDE, select the Web Pages node in
the Projects window and press Ctrl-V). The file is added to your project.
2. Link the stylesheet to your JSP pages by adding a reference between the <head> tags of
both [Link] and [Link]:

<link rel="stylesheet" type="text/css" href="[Link]">

Running the Application


1. In the Projects window, right-click the project node and choose Run. The IDE builds the web
application and deploys it, using the server you specified when creating the project. The browser
opens and displays the [Link] page. Type in some data that should fail validation, i.e., either
leave either field blank, or enter an email address with a missing '@' sign:

40
Figure 13. Form contains data that will fail validation

When you click Login, the login form page redisplays, containing an error message:

Figure 14. Form redisplays with error message

Try entering data that should pass validation. Upon clicking Login, you are presented with the success
page:

Figure 15. Success page displays showing input data

8. Implementing database connectivity in struts


The database table data fetch in tabular form through struts 2.0 and JDBC application
example.

41
Tools Required to connect the database in struts 2.0 framework. Following tools are
required to connect database
1. Struts 2.0.9
2. Database: Oracle10g
3. Tomcat 6.0

Directory Structure of Database connection Example in Struts 2.0 Using MyEclipse


IDE
[Link]

<html>
<head><title>R4R User List</title></head>
<body><br><br><center>
<a href="fetch">User List Data Fetch</a>
</center>
</body>
</html>

[Link]

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="2.5"
xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<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>

[Link]

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "[Link]
<struts>
<package name="damo" extends="struts-default">
<action name="fetch" class="[Link]">
<result name="success">/[Link]</result>
</action>
</package>
</struts>

[Link]

package org.r4r;

42
import [Link];

public class UserListAction {


private UserList userlist;
private List<UserList> userlistlist;
DAO dao=new DAO();
public String execute(){
userlistlist=[Link]();
return "success";
}
public UserList getUserlist() {
return userlist;
}
public void setUserlist(UserList userlist) {
[Link] = userlist;
}
public List<UserList> getUserlistlist() {
return userlistlist;
}
public void setUserlistlist(List<UserList> userlistlist) {
[Link] = userlistlist;
}

[Link]

package org.r4r;

public class UserList {


String name;
String address;
String city;
String state;
public UserList() {
super();
// TODO Auto-generated constructor stub
}
public UserList(String name, String address, String city, String
state) {
super();
[Link] = name;
[Link] = address;
[Link] = city;
[Link] = state;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getAddress() {
return address;

43
}
public void setAddress(String address) {
[Link] = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
[Link] = city;
}
public String getState() {
return state;
}
public void setState(String state) {
[Link] = state;
}

[Link]

package org.r4r;

import [Link];
import [Link];
import [Link];
import [Link].*;

public class DAO {


public List<UserList> fetch(){
try{
Connection con=[Link]();
PreparedStatement stmt=[Link]("select * from userlist");
ResultSet rset=[Link]();
UserList userlist;
List<UserList> list=new ArrayList<UserList>();
while([Link]()){
userlist=new UserList();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link](userlist);
}
return list;
}catch(Exception e){
[Link](e);
}
return null;
}

[Link]

package org.r4r;

44
import [Link];
import [Link];

public class ConnectionProvider {


public static Connection getConnection(){
Connection con=null;
try{
[Link]("[Link]");
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system","system");
}catch(Exception e){
[Link](e);
}
return con;
}
}

[Link]

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

<html>
<head><title>User Data Fetch in Tabular Form</title></head>
<body>
<table cellpadding="0" cellspacing="0" border="2">
<tr><th>Name</th><th>Address</th><th>City</th><th>State</th></tr>
<s:iterator value="userlistlist" var="userlist">
<tr><td><s:property value="name"/></td><td><s:property value="address"/></td>
<td><s:property value="city"/></td><td><s:property value="state"/></td></tr>
</s:iterator>
</table>
</body>
</html>

Output

[Link] a web site and prepare the SEO report of the website including
status of following factors: Title tag, meta-description tag, header

45
tags, keyword consistency, number of back links, [Link] and xml
sitemaps then after going through the steps of SEO prepare the report
SEO ranking (search engine optimization ranking) refers to a webpage’s position
in search engines’ organic search results for a given search query.

If your page is higher in search results, more people are likely to see it. Which
means more people may visit your site.

For example, look at Google’s top search results for the keyword “best gaming
chairs.”

The first two results are paid ads. After that, one of PC Gamer’s pages holds the
No. 1 organic result. This means PC Gamer has the No. 1 SEO rank on this
particular search engine results page (SERP).

And it’ll likely receive more traffic than those ranking below.

46
Why Are Search Rankings Important?
Getting better rankings for your pages is one of the main goals of SEO. Why?
Because it usually results in getting more organic traffic to your website.

To put it simply: Better rankings = more visitors.

This also serves your strategic marketing and business goals, such as:

 Increased brand awareness: Higher search rankings make your website more
visible, allowing more people to discover and learn about your business. This
boosts brand recognition and trust over time.
 More sales: More visitors naturally leads to more sales and conversions, as a
percentage of those visitors will likely purchase your products or services
 Lower customer acquisition costs: Organic traffic is essentially free,
especially compared to other paid advertising channels. Higher organic traffic
volumes lower your overall cost of acquiring customers over the lifetime of your
business.

Because of all these benefits, having higher search rankings is extremely


important today.

How to Improve Your SEO Rankings


To improve your SEO rankings, we recommend taking a holistic approach to search
engine optimization.

Don’t focus on just one factor (for example, getting more backlinks). Instead, take a
comprehensive look at all the aspects of your website’s SEO. And try to improve in all
the main areas.

Let’s take a look at the basic areas you need to improve in order to rank better.

We’ll also provide actionable tips on how to use Semrush tools in each step. Feel free
to create a free account (no credit card needed) so you can follow along.

47
13. Discuss any five tools to prepare the list of ten organic key
words for SEO purpose.

The Best Tools For Keyword Research


1. Semrush
One of the most popular keyword research tools on the market, Semrush offers a comprehensive
suite of SEO tools.

Specifically for keyword research, it includes:

 Keyword Overview: Just like its name suggests, this provides an overview of keywords, including search
volume, difficulty, CPC, and variations.

 Keyword Magic Tool: This tool gives you keywords by broad match, exact match, phrase match, and
related words, alongside relevant metrics about search volume, intent, and competitiveness.

 Keyword Manager: Only available to paid Semrush users, this tool supports deep analysis and data export.

 Position Tracking: This feature allows you to monitor how your site is ranking alongside the competition
on a daily basis.

 Organic Traffic Insights: Combining Google Analytics and Search Console with its own data, this helps you
identify the keywords that are actually driving organic traffic to your site.

Price: $99.95-449.95/month

2. Ahrefs Keywords Explorer


Another all-in-one SEO toolkit, Ahrefs includes a Keyword Explorer that provides incredibly in-
depth information on keywords.

Using data from 10 different search engines, it provides more than keyword suggestions; it also
provides information about search volume, ranking difficulty, and keyword movement.

Particularly useful is the insight it provides into your competition, helping you identify which
keywords they’re ranking for that you’re not.

This information can then be used to create new content to target and capture that traffic.

48
Price: $83-999/month

3. Google Keyword Planner


It’s only logical that the world’s most dominant search engine would provide a tool to help you
identify useful keywords.

Google Keyword Planner doesn’t offer as much functionality as some of the other tools out there,
but it does have something they don’t: direct data from Google.

Primarily intended for digital marketers who are advertising on Google, it’s a free-to-use tool for
anyone with a Google Ads account.

Using it is simple – just type in a keyword and it will give you data on approximate monthly
searches, related keywords, and bidding information.

Price: Free with a Google Ads account.

4. Serpstat
Another full-service SEO suite, Serpstat includes tools for link building, PPC campaign
management, and local search optimization, as well as keyword research.

Claiming to use the biggest database, it can help you identify keywords, analyze volume, popularity,
and competition, and track your competition.

What’s really cool about Serpstat is that its results include the site in the featured snipped as the first
result, to help you claim that spot for your own.

It also includes tools for monitoring trending keywords, including searches by region, rank tracking,
and content analysis.

Price: $59-499/month

5. [Link]
The most useful part of [Link] is the sheer volume of keyword suggestions it provides.

A search for [pharmacy], for example, returned 669 total keywords.

49
These words are provided with all the relevant data an SEO professional could want, including
competition (both average and by specific keyword), search volume, and trend information.

Screenshot from [Link], February 2023

[Link] also allows you to filter results based on your needs. You can specify region,
language, platform, and even type.

Like most of the other keyword research tools listed here, it allows you to analyze your competitors
and identify words and phrases that they’re ranking for, but you are not.

Price: $69-129/month

50

You might also like