Advanced Java Practical File
Advanced Java Practical File
(PGCA1922)
PRACTICAL FILE
1
Advanced Java Lab Index
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.
3
HTTP Description
Request
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.
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.
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.
5
Implementation: The setContentType() and getWriter() methods of the ServletResponse interface
were utilised in the example below.
A. File: [Link]
HTML
</form>
</body></html>
import [Link].*;
import [Link].*;
import [Link].*;
throws ServletException,IOException
[Link]("text/html");PrintWriter pwriter=[Link]();
} }
6
C. [Link]
XML
<web-app>
</servlet>
</servlet-mapping>
</web-app>
Output:
First 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.
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.
Cookie(String name, String value) constructs a cookie with a specified name and value.
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.
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. }
[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.
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.
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.
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.
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.
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>
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 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,
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.
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.
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]
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.
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.
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.
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.
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:
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 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).
<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>
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"%>
This is a simple JSP page where we are adding error message and including login page in response.
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.
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.
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.
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: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.
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:form>
*Note: *You can safely delete the <thead> table row, as it is not used in this tutorial.
<tr>
</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>
</tr>
<html:form action="/login">
<table border="0">
<tbody>
31
</tbody>
</table>
</html:form>
<title>Login Success</title>
</head>
<body>
<h1>Congratulations!</h1>
</body>
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.
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-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:
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.
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.
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-mappings>
Implementing Validation
In the Source Editor, browse through the LoginAction class and look at the execute method:
throws Exception {
return [Link](SUCCESS);
Notice the definition of SUCCESS, listed beneath the LoginAction class declaration:
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.
35
// extract user data
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
return [Link](FAILURE);
throws Exception {
// perform validation
return [Link](FAILURE); }
36
return [Link](SUCCESS); }
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.
// error message
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>"; }
<html:form action="/login">
<table border="0">
<tbody>
1. In LoginAction, within the if conditional clause, add a statement to set the error message
before forwarding the failure condition (changes in bold):
*[Link]();*
return [Link](FAILURE);
37
}
throws Exception {
[Link]();
return [Link](FAILURE);
return [Link](SUCCESS);
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:
Click Add. Note that the following forward entry was added to [Link] (changes in bold):
</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]"/>
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]:
40
Figure 13. Form contains data that will fail validation
When you click Login, the login form page redisplays, containing an error message:
Try entering data that should pass validation. Upon clicking Login, you are presented with the success
page:
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
<html>
<head><title>R4R User List</title></head>
<body><br><br><center>
<a href="fetch">User List Data Fetch</a>
</center>
</body>
</html>
[Link]
[Link]
[Link]
package org.r4r;
42
import [Link];
[Link]
package org.r4r;
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].*;
[Link]
package org.r4r;
44
import [Link];
import [Link];
[Link]
<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.
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.
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.
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
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
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.
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.
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.
[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