http://www.developer.com/java/web/article.php/3888666/Developing-a-Struts-Application-with-the-NetBeans-IDE.htm
You know 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. But did you know that Struts has been integrated into the NetBeans IDE since version 6.7? The current version (as of this writing) is version 6.9 and the example in this article uses NetBeans 6.8. If you were unaware of the Struts/NetBeans IDE integration, this article will walk you through the NetBeans interfaces and wizards for developing a simple Struts login application. Before starting, you need to download NetBeans 6.8 or higher (try the Java Web and EE release). Remember that you do not need to explicitly download Struts, because Struts 1.3.8 is already bundled in the NetBeans IDE. After you start NetBeans, you can create a Struts application stub with a few simple steps as follows (NetBeans automatically generates this application, which you can consider the starting point for any Struts application):
Below the Frameworks panel, you will find the following set of configuration settings for Struts (do not modify any): 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. For starters, 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 latter, which displays a simple welcome message. As stated in the introduction, you will develop a simple login application. Now, that you have the stub it is time to go further and start developing the login.jsp page, which will render the login form. For this, you can create a new JSP page and delete the welcomeStruts.jsp, or you can try to modify this existing page. First you will employ the second option, and in the next section you will develop a JSP page from scratch. Here are the steps of transforming the welcomeStruts.jsp into login.jsp:
Now that you have completed the renaming and fixed the navigation to your login.jsp page, it's time to add some real content to it. In this case, you will render a simple login form mapped in a simple HTML table (note that you can speed up the development of this table by using the NetBeans Palette -- if it is not clear that you can activate it from the Window menu). When you type in the Source Editor, NetBeans provides you with code completion for Struts tags, as well as the Struts Javadoc. You can also invoke code completion manually by pressing Ctrl-Space. Figure 4 presents a simple capture of inserting a Struts form into your page.
Now, the login.jsp page code looks like this (typical Struts application code): 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. Follow these steps: 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 and it looks like this: 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, your bean will be pretty short and simple (note that in Struts parlance, "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.execute method is called."). Here are the steps for creating it:
For now, comment the validate method and read further. You will deal with this method in validation section. Your next task is to generate an Action class and implement the For starters, follow the steps below to generate an Action stub: 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: Going further, you must add a behavior to the execute method. You have a simple scenario: the login credentials should be an email address of "admin@yahoo.com" and a password of "admin." If the provided credentials match these, then you forward the user to success.jsp, if not to failure.jsp. The code looks like this after you have used the generated code and added the needed lines:
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: Bottom of LoginActionForm, you have a validate method generated by the IDE (you will find a comment there, which you have to uncomment first). 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: 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! In Figure 8, you can see a simple test of the validation process.
The NetBeans IDE provides great support for developing Struts applications, and it is a pleasure to work with in the production stage. When you discover and utilize the other facilities of NetBeans, you will have the perfect IDE for developing amazing Java-based Web applications. Anghel Leonard is a senior Java developer with more than 13 years of experience in Java SE, Java EE, and the related frameworks. He has written and published dozens of articles about Java technologies and two books about XML and Java (one for beginners and one for experts).
Developing a Struts Application with the NetBeans IDE
June 20, 2010
Creating the Struts Application Stub in NetBeans Style
Click here for larger image
Figure 1. Starting a New Web Project in NetBeans IDE
Click here for larger image
Figure 2. Adding Struts Framework to Your Web Project
What the Generated Stub Contains?
Creating the Login.jsp Page from WelcomeStruts.jsp
<jsp:forward page="Login.do"/>
Figure 3. NetBeans IDE Navigator Panel<global-forwards>
<forward name="login" path="/Login.do"/>
</global-forwards>
<action-mappings>
<action path="/Login" forward="/login.jsp"/>
</action-mappings>
Click here for larger image
Figure 4. Sample of Struts Code Completion and Javadoc<%@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">
<thead>
<tr>
<th>Login to your site</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Email:</td>
<td><html:text property="email" /></td>
</tr>
<tr>
<td>Password:</td>
<td><html:password property="pass" /></td>
</tr>
</tbody>
</table>
<html:submit value="Login" />
</html:form>
</body>
</html:html>Creating the Success.jsp Page
<%@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
<%@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>Login Failure</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
Click here for larger image
Figure 5. Adding a Struts ActionForm Bean
Click here for larger image
Figure 6. Configure Struts ActionForm Bean<form-bean name="LoginActionForm" type="com.myapp.struts.LoginActionForm"/>
private String email;
private String pass;
Implementing the Business Logic in Struts Style
execute method. In Struts parlance: "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.
<action input="/login.jsp" name="LoginActionForm" path="/login" scope="request" type="com.myapp.struts.LoginAction"/>
/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request you are processing.
* @param response The HTTP Response you are processing.
* @throws java.lang.Exception
* @return
*/
@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("admin@yahoo.com")) && (pass.equals("admin"))){
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.):
Click here for larger image
Figure 7. Add a Struts Forward<action input="/login.jsp" name="LoginActionForm"
path="/login" scope="request" type="com.myapp.struts.LoginAction">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
Implementing the Validate Method of the LoginActionForm
Author Note: Remember that Struts has powerful support for validating dates. Check out the specialized tutorials for more information.
@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;
}
Figure 8. Running the Login Application SampleConclusion
Code Download
About the Author