Tuesday, 27 March 2012

creating a jsp page layout


How to create Netbeans Visual Web Page Layout Plugin

In my earlier article, Creating a CSS Based Fixed Page Layout, I've shown how to create your own Page Layout. In this article, I'll show how to add your Page Layout as a Netbeans template, so that it would appear in the New Visual Web Page Wizard for you to pick and create your page. We will be creating a plugin, which on installation will add your pre-defined Page Layout to the New Visual Web Page Wizard.  The created plugin will be  similar to the popular Netbeans plugin "Visual Web Page Layouts".
Download: Finished project for this plugin - PageLayoutTemplatePlugin.zip
Creating the Plugin
Creating a Netbeans plugin is extremely easy. It is a matter of few mouse clicks and key strokes. Let us start with creating a plugin project.  Here are the steps
  • Download and install Netbeans 6.0
  • Click on the New Project button in the toolbar.
  • In the New Project dialog select the category Netbeans Module and project type Module.
    Module Project
  • Specify values in the wizard panel fields as
    • Project Name: MyPageLayoutTemplates
    • Code Base Name: com.sample.pagelayouts
    • Module Display Name: My Page Layout Templates
  • Click finish to create the plugin project.
Netbeans creates the skeleton plugin project and loads it in the project explorer. You'd notice, Netbeans has created the several files including the package  com.sample.pagelayouts. Expand this package and you'll see two important files
  • layer.xml - Layer file for the plugin
  • Bundle.properties - Localizing bundle for the contents in the plugin layer 
Adding contents to the plugin 
Next step is to create the Netbeans template from the the Page Layout web page  we created earlier, including JSP, Java and related resources. Let us place our template files in a folder called "resources".
  • Right click on the package com.sample.pagelayouts and select New -> Other -> Folder
    • In the wizard specify the Folder Name as resources
  • Copy the JSP and Java files corresponding to the Page Layout in to this folder and rename the files as
    • PageLayout1.jsp ->PageLayout1.jsp.template
    • PageLayout1.java ->PageLayout1.java.template
      Note: Netbeans may not let you rename in the project view. So try in the Operating System  level.
  • Add the resources used by the Page Layout
    • Zip up the resources used by the Page Layout such as images, CSS and JavaScript files.
      Note: The contents of the zip will be unzipped in to the "resources" folder in the visual web project. My suggestion is to create unique relative folder for the resources to avoid clashing with existing items inside the "resources" folder.
    • Name the zip as PageLayout1-resources.zip
We just copied and renamed the files PageLayout1.jsp.template and PageLayout1.java.template They are not templates yet. Next step is to convert them in to actual templates. Netbeans uses Free Marker  templating Engine.
Converting to template file
Java File:
  • Specify template for "package" statement which is needed only if the template is instantiated under a package. Replace the statement
    package com.sample.pagelayouts;
    with
    <#if package?? && package != "">
      package ${package};
    </#if>
  • Now, replace the "class" definition with template
    public class PageLayout1 extends AbstractPageBean {
    with
    public class ${name} extends AbstractPageBean {
  • Replace the constructor with template
    public PageLayout1() {
    with
    public ${name} () {
JSP File:
The # (pound) symbol is a  predefined special character for FreeMarker templating enginer. So we need to replace all # character with ${pound} template and tell the engine to replace it while instantiating the template. So at the top of the file insert the assignment as
<#assign pound = '#'>
  • Specify template for encoding. Replace
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:directive.page contentType="text/html;charset=UTF-8" 
    pageEncoding="UTF-8"/>
    with
    <?xml version="1.0" encoding="${encoding}"?>
    <jsp:directive.page contentType="text/html;charset=${encoding}" 
        pageEncoding="${encoding}"/>
  • Now replace all component binding with templated binding.
    Note: If you are using NB 6.1 (M1), you need not have to do this part as the bindings are not inserted by defaultExample: Replace
    <webuijsf:page binding="#{PageLayout1.page1}" id="page1">
    with
    <webuijsf:page binding="${pound}{${folder}${name}.page1}" id="page1">
Adding template information to layer file
Ok, we are ready with the templates. Now we need to put the info about these templates in to the layer file so that they would appear in the New Visual Web Page Wizard.
<filesystem>
  <folder name="Templates">
    <folder name="PageLayoutTemplates">
      <file name="PageLayout1.jsp" 
            url="/com/sample/pagelayouts/resources/PageLayout1.jsp.template">
        <attr name="SystemFileSystem.localizingBundle" 
              stringvalue="com.sample.pagelayouts.Bundle"/>
        <attr name="name" stringvalue="PageLayout1" />
        <attr name="icon" 
              urlvalue="nbresloc:/com/sample/pagelayouts/resources/
                                                   PageLayout1-icon.jpg" />
        <attr name="previewImage" 
              urlvalue="nbresloc:/com/sample/pagelayouts/resources/
                                                   PageLayout1-preview.jpg" />
       <attr name="resources" 
            urlvalue="nbresloc:/com/sample/pagelayouts/resources/
                                                   PageLayout1-resources.zip" />
       <attr name="position" intvalue="10000"/>
       <attr name="pageLayoutTemplate" boolvalue="true"/>
       <attr name="description" stringvalue="PageLayout1_Desciption"/>
       <attr name="javax.script.ScriptEngine" stringvalue="freemarker"/>
     </file>
     <file name="PageLayout1.java" 
              url="/com/sample/pagelayouts/resources/PageLayout1.java.template">
       <attr name="position" intvalue="20000"/>
      <attr name="javax.script.ScriptEngine" stringvalue="freemarker"/>
     </file>
   </folder> <!-- Page Templates -->
  </folder> <!-- Templates -->
</filesystem>
Couple of things to note in the information we entered above
Folder: Template/PageLayoutTemplates - This is the pre-defined folder where the New Visual Web Page Wizard will look for new templates
File: PageLayout1.jsp (page) & PageLayout1.java (page bean) - These are the two actual templates that will be instantiated by the wizard.
Attributes:
  • icon: The small icon (32x32) that appears besides the name of the template in the list. The localized name will be obtained from the bundle specified via the attribute  SystemFileSystem.localizingBundle
  • previewImage: The large (128x128) icon appears in the preview area of the select template panel
  • resources: Points to the resources zip url that will be unzipped in the "resources" folder of the web application.
  •  pageLayoutTemplate - tells the wizard that this the page template (PageLayout1.java is just the page bean)
  • description:  Description of the Page Layout template. Used as a key to obtain the localized value from the bundle file
  • position: This is used to order the layout in the list. Be diligent about using a value that would not be clashing with Page Layouts provided by others too.
  •  javax.script.ScriptEngine: This is to tell the wizard which scripting engine to be used to instantiate the template.   
Open the bundle file (com.sample.pagelayouts.Bundle.properties) to include the values for the keys we used above
PageLayout1=A simple nice my own Page Layout
PageLayout1_Desciption=Creates page with my own very nice simple Page Layout 
Testing the Plugin
You can test the plugin by directly installing it in the development IDE.
  • Right click on the project node and select "Install/Reload in Development IDE"
  • Create a Visual Web Application
  • Create a new Visual Web page. In the Wizard you should see the Page Layout you added through the plugin as shown below. The created page should look the template you created.
Page Layout In Wizard
Creating the NBM 
Finally, create the NBM to be installed using plugin manager. Right click on the project node and select "Create NBM". The Created NBM is placed in the build folder as com-sample-pagelayouts.nbm




http://www.winstonprakash.com/articles/netbeans/page_layout_template_module.html 

Monday, 19 March 2012

scroll clock code

var h1, h2, m1, m2, s1, s2;
window.addEvent('domready', function() {
 if ($('custom-scrollbar-css')) $('custom-scrollbar-css').dispose();
 //
 h1=new Digit();
 h2=new Digit();
 m1=new Digit();
 m1.pushRight();
 m2=new Digit();
 s1=new Digit();
 s1.pushRight();
 s2=new Digit();
 $('main').adopt(h1.getElement(), h2.getElement(), m1.getElement(), m2.getElement(), s1.getElement(), s2.getElement());
 showTime();
 setInterval('showTime()', 1000);
});
function showTime() {
 var now=new Date();
 h1.show(now.getHours()/10);
 h2.show(now.getHours());
 m1.show(now.getMinutes()/10);
 m2.show(now.getMinutes());
 s1.show(now.getSeconds()/10);
 s2.show(now.getSeconds());
}
var barDim=120;
var sbDim=18;
var Bar = new Class({
 initialize: function(dir) {
  this.dir = dir;
  var dim=dir=='v' ? barDim : (Browser.Engine.gecko ? barDim : barDim+sbDim);
  this.holder=new Element('div', {styles:{width:dir=='h' ? dim : sbDim, height:dir=='h' ? sbDim : dim, overflow:'auto', float:'left'}});
  this.content=new Element('div', {html:'&nbsp;'});
  this.activate(true, true);
  this.holder.adopt(this.content);
 },
 activate:function(b, now) {
  var side=this.dir=='h' ? 'width' : 'height';
  if (now) this.content.setStyle(side, b ? barDim+sbDim : barDim/2);
  else this.content.tween(side, b ? barDim*2 : barDim/2);
 },
 getElement:function() {
  return this.holder;
 }
});
var HBar = new Class({
 Extends: Bar,
 initialize: function(){
  this.parent('h');
  this.holder.setStyles({'margin-left': sbDim, 'margin-right': sbDim});
 }
});
var VBar = new Class({
 Extends: Bar,
 initialize: function(){
  this.parent('v'); 
 },
 pushRight:function() {
  this.holder.setStyle('margin-left', barDim);
 }
});
var Digit=new Class({
 initialize: function() {
  var holder=this.holder=new Element('div', {styles:{width: barDim+2*sbDim, float:'left', 'margin-right':20}});
  this.bars=[new HBar(), new VBar(), new VBar(), new HBar(), new VBar(), new VBar(), new HBar()];
  this.bars[2].pushRight();
  this.bars[5].pushRight();
  this.bars.each(function(it) {holder.adopt(it.getElement());});
  this.lights=[
   [1, 1, 1, 0, 1, 1, 1],//0
   [0, 0, 1, 0, 0, 1, 0],//1
   [1, 0, 1, 1, 1, 0, 1],//2
   [1, 0, 1, 1, 0, 1, 1],//3
   [0, 1, 1, 1, 0, 1, 0],//4
   [1, 1, 0, 1, 0, 1, 1],//5
   [1, 1, 0, 1, 1, 1, 1],//6
   [1, 0, 1, 0, 0, 1, 0],//7
   [1, 1, 1, 1, 1, 1, 1],//8
   [1, 1, 1, 1, 0, 1, 1] //9
  ];
 },
 show: function(n) {
  n=Math.floor(n);
  n=n%10;
  var light=this.lights[n];
  this.bars.each(function(it, index) {
   it.activate(light[index]==1);
  });
 },
 pushRight:function() {
  this.holder.setStyle('margin-left', '50px');
 },
 getElement:function() {
  return this.holder;
 }
});

jsp cheatsheet



Thursday, 15 March 2012

jsp login page creation in eclipse


JSP - Servlets: Full Login Example

In this section we are going to discuss the implementation of a complete Login application (We received the source code of this application through Amira Thabet)
The application will
  • Ask the user to input his "username" and "password"
  • Check the existence of this user in the Data Base
    • If exists, Retrieve his first name and last name from the DB and display them
    • If not registered, Display "Sorry, you are not registered"
You are assumed to know about the connection between java and DB.
This Login application uses the so called "JavaBeans" and "DAOs" - standing for Data Access Objects - to handle the interactions with the DB.
Beans are normal java classes containing
  1. Attributes
  2. Getters and Setters for such attributes (and may be some additional methods)
In our application, Beans are used to save data needed in the application (in the form of variables) . This data may be a representation of data existing in the DB, data entered by the user, or results of business logic.
DAOs are objects responsible for handling the interactions with the Data Source, through implementing the access mechanism required to work with the data source.
In our application the DAO is responsible for
  1. Reading data from the Bean (data entered by the user) and checking its consistency with the DB - use Getters to get values of variables from the bean-
  2. Retrieving data from the DB and saving it to the Bean - use Setter methods to set values to variables
As mentioned in the application description, the user will have to enter his username and password, so first of all, we need a JSP that asks the user to input his username and password in their corresponding fields.
To have this JSP, please follow these steps:
  • Open eclipse
  • Create a new "Dynamic Web Project"
  • Name it "LoginExample"
  • Create the JSP
    • In the "Web Content" folder, create a new JSP
    • Name it "LoginPage"
    • Place this code
    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <!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=windows-1256"> <title>Login Page</title> </head> <body> <form action="LoginServlet"> Please enter your username <input type="text" name="un"/><br> Please enter your password <input type="text" name="pw"/> <input type="submit" value="submit"> </form> </body> </html>
As you can see; (in the LoginPage) when the user submits, the JSP calls "LoginServlet".This LoginServlet is intended to handle the Business logic associated with the request.
Create the LoginServlet by following these steps:
  • In the "src" folder, create a new "Package"
  • Name it "ExamplePackage"
  • In the "ExamplePackage", create a new "Servlet"
  • Name it "LoginServlet"
  • Place this code
    import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { try { UserBean user = new UserBean(); user.setUserName(request.getParameter("un")); user.setPassword(request.getParameter("pw")); user = UserDAO.login(user); if (user.isValid()) { HttpSession session = request.getSession(true); session.setAttribute("currentSessionUser",user); response.sendRedirect("userLogged.jsp"); //logged-in page } else response.sendRedirect("invalidLogin.jsp"); //error page } catch (Throwable theException) { System.out.println(theException); } } }
The login servlet instantiates a Bean that is of type "UserBean", and then calls the DAO named "UserDAO".
  • Our UserBean is a class representing the User table in our Database (where each column in the user table has a corresponding instance variable with a setter and a getter method).
  • The DAO, as said before, contains methods needed to communicate with the data source. In our example, the only needed method is the login method that checks if the username and password inputted by the user are valid or not.
Before implementing the DAO, you need to prepare your Data Source.
  1. Create a table in your DB
  2. Name it users
  3. Create the columns: 'FirstName', 'LastName', 'username', and 'password'
  4. Refer to your DB as a data source from "Administrative tools" in Control Panel
Please follow these steps to implement the Bean and the DAO
  • Create the "UserBean" class
    1. In the " ExamplePackage ", create a new "Class"
    2. Name it "UserBean"
    3. Place this code
      public class UserBean { private String username; private String password; private String firstName; private String lastName; public boolean valid; public String getFirstName() { return firstName; } public void setFirstName(String newFirstName) { firstName = newFirstName; } public String getLastName() { return lastName; } public void setLastName(String newLastName) { lastName = newLastName; } public String getPassword() { return password; } public void setPassword(String newPassword) { password = newPassword; } public String getUsername() { return username; } public void setUserName(String newUsername) { username = newUsername; } public boolean isValid() { return valid; } public void setValid(boolean newValid) { valid = newValid; } }
  • Create the "UserDAO" class
    1. In the " ExamplePackage ", create a new "Class"
    2. Name it "UserDAO"
    3. Place this code
      import java.text.*; import java.util.*; import java.sql.*; public class UserDAO { static Connection currentCon = null; static ResultSet rs = null; public static UserBean login(UserBean bean) { //preparing some objects for connection Statement stmt = null; String username = bean.getUsername(); String password = bean.getPassword(); String searchQuery = "select * from users where username='" + username + "' AND password='" + password + "'"; // "System.out.println" prints in the console; Normally used to trace the process System.out.println("Your user name is " + username); System.out.println("Your password is " + password); System.out.println("Query: "+searchQuery); try { //connect to DB currentCon = ConnectionManager.getConnection(); stmt=currentCon.createStatement(); rs = stmt.executeQuery(searchQuery); boolean more = rs.next(); // if user does not exist set the isValid variable to false if (!more) { System.out.println("Sorry, you are not a registered user! Please sign up first"); bean.setValid(false); } //if user exists set the isValid variable to true else if (more) { String firstName = rs.getString("FirstName"); String lastName = rs.getString("LastName"); System.out.println("Welcome " + firstName); bean.setFirstName(firstName); bean.setLastName(lastName); bean.setValid(true); } } catch (Exception ex) { System.out.println("Log In failed: An Exception has occurred! " + ex); } //some exception handling finally { if (rs != null) { try { rs.close(); } catch (Exception e) {} rs = null; } if (stmt != null) { try { stmt.close(); } catch (Exception e) {} stmt = null; } if (currentCon != null) { try { currentCon.close(); } catch (Exception e) { } currentCon = null; } } return bean; } }
The DAO uses a class named "ConnectionManager" to get a connection with the DB.
Create the "ConnectionManager" class:
  1. In the " ExamplePackage ", create a new "Class"
  2. Name it "ConnectionManager"
  3. Place this code
    import java.sql.*; import java.util.*; public class ConnectionManager { static Connection con; static String url; public static Connection getConnection() { try { String url = "jdbc:odbc:" + "DataSource"; // assuming "DataSource" is your DataSource name Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { con = DriverManager.getConnection(url,"username","password"); // assuming your SQL Server's username is "username" // and password is "password" } catch (SQLException ex) { ex.printStackTrace(); } } catch(ClassNotFoundException e) { System.out.println(e); } return con; } }
  4. In the pasted code, Replace
    • "DataSource" with your Data Source name
    • "username" with your SQL Server username
    • "password" with your SQL Server password
Finally, we are done with the logic and accessing the DB. So back to the interface, we need two JSPs; one for the valid login and another for the invalid. The two JSPs are
  • userLogged.jsp: Displays a message to welcome the user, using his first and last names (retrieved from the DB)
  • invalidLogin.jsp: Displays a message to inform the user that he is not a registered user
Steps to create the "userLogged" JSP
  1. In the "WebContent" folder, create a new "JSP"
  2. Name it "userLogged"
  3. Place this code
    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" import="ExamplePackage.UserBean" %> <!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=windows-1256"> <title> User Logged Successfully </title> </head> <body> <center> <% UserBean currentUser = (UserBean (session.getAttribute("currentSessionUser"));%> Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %> </center> </body> </html>
Steps to create the "invalidLogin" JSP
  1. In the "WebContent" folder, create a new "JSP"
  2. Name it "invalidLogin"
  3. Place this code
    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <!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=windows-1256"> <title>Invalid Login</title> </head> <body> <center> Sorry, you are not a registered user! Please sign up first </center> </body> </html>
Run the application , If you do not know any of the following steps, please check Steps 5-8 in the JSP Example
  • Set LoginPage.jsp to be your Home page (from web.xml)
  • Add your Project to Tomcat
  • Start Tomcat
  • Go to http://Localhost/loginExample
  • Test your project
This should be the result

Tuesday, 13 March 2012

jsp login page creation using structs

Tutorial to create a login page using structs in netbeans


To complete this tutorial, you need the following software and resources.
Software or ResourceVersion Required
NetBeans IDE6.8, 6.9, 7.0, 7.1, Java EE bundle
Java Development Kit (JDK)6
GlassFish server
or
Tomcat servlet container
Open Source Edition 3.x

version 6.x or 7.x
Notes:
  • The Java installation enables you to optionally install the GlassFish server and the Apache Tomcat servlet container. You must install one of these (or register a different server in the IDE) to work through this tutorial.
  • If you need to compare your project with a working solution, you can download the sample application.

Overview of the Application

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 web.xml deployment descriptor as shown below. The controller servlet uses a struts-config.xml 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.
Struts workflow
Developing a Struts application is similar to developing any other kind of web application in NetBeans IDE. However, you complement your web development toolkit by taking advantage of the Struts support provided by the IDE. For example, you use templates in the IDE to create Struts Action objects and ActionForm beans. Upon creation, the IDE automatically registers these classes in the struts-config.xml file and lets you extend this file very easily using menu items in the Source Editor's right-click menu. Because many web applications use JSP pages for the view, Struts also provides custom tag libraries which facilitate interaction with HTML forms. Within the IDE's Source Editor, you can invoke code completion and Javadoc support that helps you to work efficiently with these libraries.
The following steps demonstrate how to create a simple form that collects user data, performs simple validation, and outputs the data on a success page.

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. Under Categories, select Web. Under Projects, select Web Application and 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. In the Frameworks panel, select Struts:
    Struts option displayed in Frameworks panel of New Web Application wizard
    For purposes of this tutorial, do not change any of the configuration values in the lower region of this panel. These are the following:
    • Action Servlet Name: The name of the Struts action servlet used in the application. The web.xml deployment descriptor contains an entry for the action servlet and specifies the appropriate Struts-specific parameters, such as the path to the servlet class within the Struts library and to thestruts-config.xml configuration file within the application.
    • Action URL Pattern: Specifies the patterns of incoming requests which are mapped to the Struts action controller. This generates a mapping entry in the deployment descriptor. By default, only the *.do pattern is mapped.
    • Application Resource: Lets you specify the resource bundle which will be used in the struts-config.xml file for localizing messages. By default, this is com.myapp.struts.ApplicationResource.
    • Add Struts TLDs: Lets you generate tag library descriptors for the Struts tag libraries. A tag library descriptor is an XML document which contains additional information about the entire tag library as well as each individual tag. In general this is not necessary, because you can refer to on-line URIs rather than local TLD files.
  5. Click Finish. The IDE creates the project folder in your file system. As with any web application in the IDE, the project folder contains all of your sources and the IDE's project metadata, such as the Ant build script. However, your web application in addition has all of the Struts libraries on its classpath. Not only are they on the application's classpath, but they are included in the project and will be packaged with it later when you build the project.
The project opens in the IDE. The Projects window is the main entry point to your project sources. It shows a logical view of important project contents. For example, if you expand several nodes within the new project, it may appear as follows:
Projects window containing newly created project
Note: Use the Files window (Window > Files) to see all of your project contents in a directory-based view.
The Struts-specific configuration files, as well as the application's deployment descriptor, are conveniently placed within the Configuration Files folder. Open the deployment descriptor (double-click the web.xml file node to have it display in the Source Editor). In order to handle Struts processing, a mapping is provided for the Struts controller servlet:
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</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>
Above, the Struts controller servlet is named action and is defined in the Struts library (org.apache.struts.action.ActionServlet). It is set to handle all requests that satisfy the *.do mapping. In addition, initialization parameters for the servlet are specified by means of the struts-config.xml file, also contained in the WEB-INF folder.

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

  1. Right-click the MyStrutsApp project node, choose New > JSP, and name the new file login. Click Finish. The login.jsp 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="http://struts.apache.org/tags-bean" prefix="bean" %>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
    Many web applications use JSP pages for views in the MVC paradigm, so Struts provides custom tag libraries which facilitate interaction with HTML forms. These can be easily applied to a JSP file using the IDE's support for code completion. When you type in the Source Editor, the IDE 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:
    Code completion and Javadoc for Struts tags provided in Source Editor
    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.
  4. 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).
  5. 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.
    Create Table dialog displayed in Source Editor
    Click OK, then optionally reformat the code (Alt-Shift-F). The form in login.jsp 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>
        </table>
    
        <html:submit value="Login" />
    
    </html:form>
    Note: You can safely delete the <thead> table row, as it is not used in this tutorial.
  6. In the first table row, enter the following (changes in bold):
    <tr>
        <td>Enter your name:</td>
        <td><html:text property="name" /></td>
    </tr>
  7. 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.
  8. 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 inbold):
    <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>
        </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 success.jsp 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>
  3. Add a bean taglib directive to the top of the file:
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
    
  4. 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).
  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 com.myapp.struts in the Package drop-down list and click Finish.
    The IDE creates the ActionForm 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 struts-config.xml file. If you open the struts-config.xml file in the Source Editor, you can see the following declaration, which was added by the wizard:
    <form-beans>
        <form-bean name="LoginForm" type="com.myapp.struts.LoginForm" />
    </form-beans>
    
    The IDE provides navigation support in the struts-config.xml file. Hold down the Ctrl key and hover your mouse over the ActionForm bean's fully qualified class name. The name becomes a link, enabling you to navigate directly to the class in the Source Editor:
    Navigation support displayed in Struts config file
  3. In the ActionForm 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 login.jsp. Because name has already been created in the ActionForm 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.
    Insert Code menu displayed 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 com.myapp.struts 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 login.jsp. Make sure settings appear as in the screenshot below, then click Next.
    New Struts Action wizard
  5. 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 struts-config.xml file:
    <action-mappings>
        <action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false"/>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
    The name and scope attributes apply to the form bean that is associated with the action. Specifically, when an incoming request matches /login, the Struts framework automatically instantiates a LoginForm object and populates it with the form data sent in the request. The default value of validate is set totrue. This tells the framework to call the validate method of the form bean. You deselected this option in the wizard however because you will hand-code simple validation in the next step, which does not require the validate method.

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 mapping.findForward(SUCCESS);
}
Notice the definition of SUCCESS, listed beneath the LoginAction class declaration:
private final static String SUCCESS = "success";
Currently, the mapping.findForward 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

  1. Type in the following code within the body of the execute method:
    // extract user data
    LoginForm formBean = (LoginForm)form;
    String name = formBean.getName();
    String email = formBean.getEmail();
    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.
  2. 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
        name.equals("") ||            // name parameter is empty
        email.indexOf("@") == -1) {   // email lacks '@'
    
        return mapping.findForward(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 = formBean.getName();
        String email = formBean.getEmail();
    
        // perform validation
        if ((name == null) || // name parameter does not exist
                email == null || // email parameter does not exist
                name.equals("") || // name parameter is empty
                email.indexOf("@") == -1) {   // email lacks '@'
    
            return mapping.findForward(FAILURE);
        }
    
        return mapping.findForward(SUCCESS);
    }
  3. Add a declaration for FAILURE to the LoginAction class (changes in bold):
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    
Using the above logic, the execute method forwards the request to the success view if the user provides an entry for both name and email fields, and the email entered contains an '@' sign. Otherwise, the failure view is forwarded. As will be demonstrated below in Adding forward Entries to struts-config.xml, you can set the failure view to point back to the form page, so that the user has another chance to enter data in the correct format.

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 login.jsp. 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;
  2. Add a getter method and a setter method for error, as demonstrated above.
  3. Modify the setter method so that it appears as follows:
    public void setError() {
        this.error =
            "<span style='color:red'>Please provide valid entries for both fields</span>";
    }
    
  4. Open login.jsp 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"/>
                        &nbsp;</td>
                </tr>
                <tr>
                    <td>Enter your name:</td>
                    <td><html:text property="name" /></td>
                </tr>
    
  5. 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
        name.equals("") ||            // name parameter is empty
        email.indexOf("@") == -1) {   // email lacks '@'
    
        formBean.setError();
        return mapping.findForward(FAILURE);
    }
    
Your completed LoginAction class should now appear as follows:
public class LoginAction extends org.apache.struts.action.Action {

    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 = formBean.getName();
        String email = formBean.getEmail();

        // perform validation
        if ((name == null) ||             // name parameter does not exist
            email == null  ||             // email parameter does not exist
            name.equals("") ||            // name parameter is empty
            email.indexOf("@") == -1) {   // email lacks '@'

            formBean.setError();
            return mapping.findForward(FAILURE);
        }

        return mapping.findForward(SUCCESS);

    }
}

Adding forward Entries to struts-config.xml

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 thestruts-config.xml file.
  1. Open struts-config.xml in the Source Editor, right-click anywhere in the action entry for LoginForm, and choose Struts > Add Forward.
    Struts options displayed in right-click menu of struts-config.xml
  2. In the Add Forward dialog box, type success in Forward Name. Enter the path to success.jsp in the Resource File field (i.e., /WEB-INF/success.jsp). The dialog box should now look as follows:
    Add Forward dialog
    Click Add. Note that the following forward entry was added to struts-config.xml (changes in bold):
    <action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false">
        <forward name="success.jsp" path="/WEB-INF/success.jsp"/>
    </action>
    
  3. Perform the same action to add a forward entry for failure. Set the Resource File path to /login.jsp. The following forward entry is added to struts-config.xml (changes in bold):
    <forward name="success" path="/WEB-INF/success.jsp"/>
    <forward name="failure" path="/login.jsp"/>
    

Configuring and Running the Application

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 login.jsp. Optionally, you can also add a simple stylesheet to the project.

Setting the Welcome Page

  1. In the Projects window, double-click the web.xml deployment descriptor. The tabs listed along the top of the Source Editor provide you with an interface to the web.xml file. Click on the Pages tab. In the Welcome Files field, enter login.jsp.
    deployment descriptor interface
    Now click on the XML tab to view the file. Note that login.jsp is now listed in the welcome-file entry:
    <welcome-file>login.jsp</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 login.jsp and success.jsp:
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    

Running the Application

login.jsp displayed in browser with sample data

  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 login.jsp 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:


    When you click Login, the login form page redisplays, containing an error message:
    login.jsp with error message displayed

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