0% found this document useful (0 votes)
68 views

Developing Web Application Using Struts Framework

The document describes how to create a web application using the Struts framework in NetBeans. It involves generating a Struts application stub which sets up the necessary configuration files and libraries. Pages like login.jsp and success.jsp are created to handle user login. An ActionForm bean stores the user credentials, and an Action class implements the login logic in its execute method. Upon successful or failed login, the user is redirected to success.jsp or failure.jsp respectively.

Uploaded by

Divya Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Developing Web Application Using Struts Framework

The document describes how to create a web application using the Struts framework in NetBeans. It involves generating a Struts application stub which sets up the necessary configuration files and libraries. Pages like login.jsp and success.jsp are created to handle user login. An ActionForm bean stores the user credentials, and an Action class implements the login logic in its execute method. Upon successful or failed login, the user is redirected to success.jsp or failure.jsp respectively.

Uploaded by

Divya Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

DEVELOPING WEB APPLICATION USING STRUTS FRAMEWORK

Struts is one of the most popular free, open-source frameworks for creating Java Web applications. You
know it's based on the Model-View-Controller (MVC) architecture to separate concerns in an application.

Creating the Struts Application Stub in NetBeans


1. Choose File  New Project  Under Categories, select Web. Under Projects, select Web Application and
click Next.

2. On this page, under the Project Name section, type login and select the location of the project. Click Next.
3. In the next panel, you can choose the server that will host this application, the Java EE version and the
context path. For this example, choose Glass Fish 4.1 server, Java EE 7 Web and do not modify the default
context path. Click Next.
4. In the Frameworks panel, select Struts 1.3.10. This is a major step because you indicate to NetBeans your
intention to use Struts. Click Finish.
Below the Frameworks panel, you will find the following set of configuration settings for Struts (do not modify
any),

 Action Servlet Name - indicates the name of the Struts action servlet (This is mapped in web.xml
descriptor.)
 Action URL Pattern - represents the incoming requests, which are mapped to the Struts action
controller (By default, only the *.do pattern is mapped in the deployment descriptor.)
 Application Resource - in this section, you may specify the resource bundle, which will be used in the
struts-config.xml descriptor
 Add Struts TLDs - lets you generate tag library descriptors for the Struts tag libraries

What the Generated Stub Contains?


After the stub it is generated, you should see the welcomeStruts.jsp page in the NetBeans editor. Before
modifying this page, consider what else was added/generated in your Struts application stub. Notice that the
Struts libraries were added in the project under the Libraries folder of the login project (see this in the Projects
tab).
Going further, you should notice the content of the Configuration Files folder, which contains the Struts-
specific descriptors (struts-config.xml, tiles-defs.xml, validation.xml, validator-rules.xml) and the application
deployment descriptor (web.xml) -- all of them were generated with minimal information but enough to have a
functional Struts application. Take the time to open these files and explore their contents.
Finally, notice the two JSP pages, index.jsp and welcomeStruts.jsp. The former contains a simple JSP-
style redirect to the webpage, which displays a simple welcome message.
Creating the Login.jsp Page from WelcomeStruts.jsp
1. Rename the welcomeStruts.jsp page by right clicking on its name in the Projects tab (under the Web
Pages folder) and choose Rename. Type the new name login.jsp without an extension and press OK.
2. Go to index.jsp and modify the redirect to login.jsp

<jsp:forward page="Login.do"/>

3. Open the struts-config.xml file and navigate to the Global Forwards section. Notice that you can navigate to
any section from this descriptor by using the NetBeans Navigator, which automatically appears by default in the
lower-lefthand corner.

4. Modify the single global forward


<global-forwards>
<forward name="login" path="/Login.do"/>
</global-forwards>

5. Navigate to the Action Mappings section and modify the single action like this:
<action-mappings>
<action path="/Login" forward="/login.jsp"/>
</action-mappings>
Login Code (login.jsp)

<%--
Document : login
Created on : Mar 2, 2019, 01:11:23 AM
Author : HARRY FERNANDEZ
--%>

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<html:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body style="background-color: white">

<html:form action="/login">
<html:errors property="wrongemail" />
<html:errors property="wrongpass" />
<table border="1">
<tr>
<th>Login</th>
<th></th>
</tr>
<tr>
<td>Email ID</td>
<td><html:text property="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><html:password property="pass" /></td>
</tr>
</table>
<html:submit value="Login" />
</html:form>

</body>
</html:html>
Creating the Success.jsp Page
When the user has successfully logged in, you must redirect the application flow to the requested page.
In this case, you render a success.jsp page, which is a very simple confirmation of the login credentials.

Create a new JSP page. In the Projects tab, expand the login project and right-click on the Web Pages folder.
Select the New | JSP ... option from the contextual menu and type "success" in the File Name section of
the New JSP File wizard. Press Finish.

<%--
Document : success
Created on : Mar 2, 2019, 01:14:34 AM
Author : HARRY FERNANDEZ
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

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


"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Successfully</title>
</head>
<body>
<h1>Login Successfully Done !!!</h1>
<p>Email: <bean:write name="LoginActionForm" property="email" />.</p>
<p>Password: <bean:write name="LoginActionForm" property="pass" />.</p>
</body>
</html>
Creating the Failure.jsp Page
When the provided credentials are wrong, you redirect the application flow to a page called failure.jsp. This is
generated in the same manner as success.jsp

<%--
Document : failure
Created on : Mar 2, 2019, 01:48:03 AM
Author : HARRY FERNANDEZ
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

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


"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Failure</title>
</head>
<body>
<h1>Oops, Login Failed !!!</h1>
<p>Email: <bean:write name="LoginActionForm" property="email" />.</p>
<p>Password: <bean:write name="LoginActionForm" property="pass" />.</p>
</body>
</html>

Creating an ActionForm Bean

A Struts ActionForm bean is perfect for storing the provided credentials between requests (or any data
provided through a form). Since you need to store the email and the password, which are two strings.
An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean
will have had its properties initialized from the corresponding request parameters before the
corresponding Action.executemethod is called.
1. In the Projects tab, right-click on the login project and select New | Other ... from the contextual menu.
2. In the New File wizard's Categories list, select the Struts category, and from the File Types list, select
the Struts ActionForm Bean type and press Next.
3. Now you have to type a name for the new action form. Type "LoginActionForm" in the Class Name section.
Also, choose the com.harry.struts package from the Package list.
4. When you press the Finish button, NetBeans will generate the new action form for you and display it in
the Source Editor. By default, this class provides it with a String called name and an int called number, along
with getter/setter methods for them called delete all, because you need to add the email and the password!
Also, if you check the struts-config.xml, you can see the new form bean added under the Form Beans section:
<form-bean name="LoginActionForm" type="com.myapp.struts.LoginActionForm"/>

5. In the LoginActionForm, add two properties,


private String email;
private String pass;

6. Add getter / setter methods for these two properties. Go below this code and right-click in an empty spot.
From the contextual menu, select Insert Code ... and Getter and Setter .... In the Generate Getters and
Setters window, select the two properties and press Generate.

Now, you should see the corresponding methods in your code.

Implementing the Business Logic in Struts Style


Your next task is to generate an Action class and implement the execute method.

In Struts, when a request is received, the Controller invokes an Action class. The Action class consults
with the Model (or, preferably, a Facade representing your Model) to examine or update the application's state.
The execute method is the "brain" of your application, because here you tell the application what to do.

1. In the Projects tab, right-click on the login project and select New | Other ... from the contextual menu.
2. In the New File wizard's Categories list, select the Struts category and from the File Types list,
select Struts Action type and press Next.
3. Now you have to type a name for the new action, Type LoginAction in the Class Name section. Also,
choose the com.harry.struts package from the Package.
4. Type /login in the Action Path section. This value must be the same as the one provided in
the action attribute of the <html:form> tag in login.jsp. Click Next.
5. In this window, you have to associate the Action with an ActionForm. By default, the IDE did that for you,
but notice that this can be done manually by selecting the corresponding ActionForm from the
list ActionForm Bean Name.
5. In addition:
 Type /login.jsp for the Input Resource field, or use the Browse button.
 Set the Scope to Request.
6. Click Finish.

Now, you should see the generated code of your action in the Source Editor. If you look in struts-config.xml, you
will notice the new added entry under Action Mappings, like this:
<action input="/login.jsp" name="LoginActionForm" path="/login" scope="request"
type="com.harry.struts.LoginAction"/>

/* forward name="success" path="" */


private static final String SUCCESS = "success";
private static final String FAILURE = "failure";

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

LoginActionForm data = (LoginActionForm)form;

String email = data.getEmail();


String pass = data.getPass();
if ((email.equals("[email protected]")) && (pass.equals("harry"))){
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}

Configure the Forwards Entries

As you can see, your action class contains two forwarding conditions, SUCCESS and FAILURE. In this
section, you configure these forwards in the struts-config.xml file as follows (Without these configurations,
Struts will not know what JSP pages to associate to the forwarding conditions. You know that SUCCESS should
be associated to success.jsp and FAILURE to failure.jsp, and now Struts will also know that.):

1. In struts-config.xml, right-click anywhere in the action entry for LoginActionForm and choose Struts |
Add Forward from the contextual menu.
2. In the Forward Name section, type "success." In the Resource File, type /success.jsp or use
the Browse button to navigate to this page. Click Add.

Repeat this process for FAILURE, but select the /failure.jsp page and type "failure" in the Forward
Name section. Now, in struts-config.xml, you should have this:
<action input="/login.jsp" name="LoginActionForm" path="/login" scope="request"
type="com.harry.struts.LoginAction">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>

Implementing the Validate Method of the LoginActionForm


Bottom of LoginActionForm, you have a validate method generated by the IDE. This method allows you
to put more reusable validation in ActionForm and return non-empty ActionErrors from validate to trigger
redisplay of input data.

Next, you add a basic validation over the provided login credentials:

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getEmail() == null || getEmail().length() < 6) {
errors.add("wrongemail", new ActionMessage("errors.email", "This email"));
}
if (getPass() == null || getPass().length() < 5) {
errors.add("wrongpass", new ActionMessage("errors.minlength", "Password", "6"));
}
return errors;
}

You're done! Now you can test the application and see how it works.
Press the Run Main Project button over the IDE main toolbar!, you can see a simple test of the validation
process.

You might also like