My Simple Struts Guide

I will add the section to install and configure struts later.

Now, let us assume that struts is installed and working.

Now let us create a sample user login screen, welcome page and error page.

The first screen will be the UserLogin.jsp and then users enter username and password.

Now we are validating the username and password against the hard coded values in the server side beans.

If the login is successful, then the request will forwared to welcome page or else to the error page.

For any struts project,

  • a) should have a bean extends to "org.apache.struts.action.ActionForm".

    This is the helper class that gets all the html element values and populates the values of the private instance variables of the bean.

  • b) another bean should extend to "org.apache.struts.action.Action", is the model component of the MVC framework that struts offers.

a) should have a bean extends to "org.apache.struts.action.ActionForm".

This is the helper class that gets all the html element values and populates the values of the private instance variables of the bean.

This bean should have setter and getter methods for all the HTML form fields.

b) another bean should extend to "org.apache.struts.action.Action", is the model component of the MVC framework that struts offers.

There is a method to be overriden,

public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)

c) the action beans and actionform beans are to be mentioned in the struts-config.xml file, and a properties file is to be created in the Root\WEB-INF\classes directory.

Let us create the UserLogin.jsp page

<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<html>
    <head><title>My First Struts Application</title></head>
    <body>
        <h3>My First Struts Application</h3>
        <html:errors/>
        <html:form action="/UserLogin.do">
            User Name:<html:text property="userName" /><br>
            Password:<html:password property="password" /><br>
        <html:submit/>
        </html:form>
    </body>
</html>

 

First four lines from top are the ways of using tag libraries, and will be discussed latter.

For the time being assume that these tag libraries are used to reduce html tags and java codes mixture and moving all the processings to he server side.

There is a form tag and the action goes to the UserLogin.do, is an alias used in the struts-config.xml file for specifying the Action bean. In our case, LoginAction.

This UserLogin.jsp when submitted pressing the submit button, handle goes to the Controller servlet of struts, this servlet reads the struts-config.xml file and goes to this section of the struts-config.xml file.

struts-config.xml

<struts-config>

    <form-beans>
        <form-bean name="loginForm" type="com.mohanjava.demo.LoginForm"/>
    </form-beans>

    <action-mappings>
        <action path="/UserLogin"
                type="com.mohanjava.demo.LoginAction"
                name="loginForm"
                scope="request"
                input="/UserLogin.jsp">

            <forward name="success" path="/welcome.jsp"/>
            <forward name="failure" path="/error.jsp"/>
        </action>
    </action-mappings>

<struts-config>

Now UserLogin.do in the UserLogin.jsp is mapped to the path="/UserLogin" action.

So the handle goes to the name="loginForm".

loginForm is declared in the struts-config.xml file as

<form-bean  name="loginForm" type="com.mohanjava.demo.LoginForm"/>

So the LoginForm is activated and the respective setter methods are called and all the instance variables are populated.

LoginForm
package com.mohanjava.demo;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public final class LoginForm extends ActionForm {

    private String userName;
    private String password;

    public void setUserName(String userName) {
	this.userName = userName;
    }

    public String getUserName() {
	return userName;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getPassword() {
	return password;
    }

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

	ActionErrors errors=new ActionErrors();
	if(userName == null || password.equals("")) {
	    errors.add("User Name:", new ActionError("error.userName"));
	    errors.add("Password:", new ActionError("error.password"));
	}
	return errors;
    }
}

At the end, validate method is called, passing the ActionMapping mapping, HttpServletRequest request. validate method creates an error in form of ActionErrors, and returns this ActionErrors.

If any error condition, this ActionErrors is used to process and show the error in the output.

In case of no error, ActionServlet calls the com.mohanjava.demo.LoginAction class and executes the perform method passing ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse as parameters.

LoginAction.java
package com.mohanjava.demo;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class LoginAction extends Action {
    public ActionForward perform(ActionMapping mapping, ActionForm form,
				 HttpServletRequest request, HttpServletResponse response) {
	LoginForm f = (LoginForm) form;
	String userName=f.getUserName();
	String password = f.getPassword();
	if((userName.equals("demo")) &&  (password.equals("password"))) {
	    return (mapping.findForward("success"));
	} else {
	    return (mapping.findForward("failure"));
	}
    }
}

Now all the values from the HTML tags are captured in the LoginAction via LoginForm class. Now processing happens here, even we can use EJBs using helper classes from this LoginAction class.

Upon completion of the processing, we call mapping.findForward("success") or mapping.findForward("failure") what so ever required.

Again ActionServlet looks at the struts-config.xml for finding out the next page as defined for "success" or "failure".

In our case success means control goes to the welcome page or else for failure it goes to the error page.

Now we have to define the properties file for the header, footer and error and any other messages.

properties file

errors.header=<h4><span style='color:red'>Validation errors</span></h4><ul>
errors.footer=</ul><hr>
error.userName=<span style='color:red'>Enter User name</span>
error.password=<li><span style='color:red'>Enter Password</span></li>

Now start the server, and go to the url http://localhost:8080/UserLogin.jsp in your browser, may be Mozilla Firefox, my favorite one.

Now you can see the login page.

If you enter the correct user name and password, the request will be forwarded to the welcome page else to the error page.