Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Monday, September 08, 2008

Cannot find ActionMappings or ActionFormBeans collection

Delicious 0
This error occurs when you try to display a JSP before the Struts ActionServlet has been initialized and is active.

read more | digg story

Saturday, September 06, 2008

Common Struts Errors and Causes

Delicious 0
This page contains errors and exceptions commonly encountered during web application development using Struts. Along with the exception or error messages themselves, potential causes of these errors are often listed along with links to additional resources.

I found this post here  and i think it will solve many problems you got when you were creating Struts Application.

To find the error you're looking for, use your browser's Find or Search capability and input a few words that you are seeing in your error message.


Cannot retrieve mapping for action
Exception: javax.servlet.jsp.JspException: Cannot retrieve mapping for action /Login
Probable Cause: No action defined in struts-config.xml to match that specified in the JSP's <html:form action="Login.do".


Cannot retrieve definition for form bean null
Exception: org.apache.jasper.JasperException: Cannot retrieve definition for form bean null
Probable Cause: This exception typically occurs because Struts cannot find the form bean it expects for a specific action according to the mapping in the struts-config.xml file. Most often, this is probably because the name given to the form in the name attribute of the form-bean element does not match the name attribute of the associated action's action element. In other words, the action and form should each have a name attribute that matches exactly, including case. It has been reported that this error has been seen when no name attribute is associated with the action. If there is no name attribute in an action element, no form is associated with the action. Others have reported this error as merely a symptom of something completely unrelated (all too common), but the mismatch of name attributes in the form-bean and action elements in the struts-config.xml file is the usual culprit.


Must specify type attribute if name is specified
Exception: Must specify type attribute if name is specified
Probable Cause:
This error is seen in conjunction with the Struts' HTML FORM tag. As the error message points out, the "name" attribute was used in the Struts HTML FORM tag (<html:form>), but the "type" attribute was not specified for this HTML FORM custom tag.

There are two easy ways to get around this:
  1. Remove name attribute altogether and specify only an action attribute, allowing Struts to figure out the form class from the struts-config.xml file.
  2. If you really want to use the name attribute, then specify the type attribute. This attribute should be set to the fully qualified (full package) class name of the class that is to be used as the ActionForm associated with the action. For example, the class attribute might be specified in the Struts HTML FORM tag as follows:




    <html:form action="someAction.do"  name="MyFormBean"
     class="org.someOrg.someApp.someClass">
    
Related Links: Struts FAQ / View / HTML


No action instance for path /xxxx could be created
Exception: No action instance for path /xxxx could be created
Probable Causes:
Special Note: Because so many different things can cause this error, it is recommended that you turn your error logging/debugging levels on your web server to a high level of verbosity to see the underlying problems in trying to instantiate the action class you have written and associated with the specified action xxxx through an action mapping in the struts-config.xml file.
Your Action class specified in the struts-config.xml file under the class attribute of the action mapping for action xxxx cannot be found for a variety of reasons, including (but not limited to):
  • Failure to place compiled .class file for the action in the classpath (needs to be under WEB-INF/classes with the appropriate directory structure underneath this that matches the package your Action class belongs to).
  • Package spelling or hierarchy specified in your action class itself (using the package keyword) does not match the spelling or complete package hierachy specified for your action class in the class attribute of the action in struts-config.xml. 
Action class specified in the /xxxx action mapping in the struts-config.xml file (class attribute) does not extend (directly or indirectly) from the Action class. In other words, your custom Action class does not extend off the Struts-provided Action class or off of another class that eventually extends the Action class (such as DispatchAction.
Problem in your classpath, such as web server not being able to find ApplicationResources.properties files in the WEB-INF/classes/ directory or specified subdirectory.
Problem in struts-config.xml file with action mapping.
Problem with data-sources.xml file.
Related Links:


Cannot find bean under name ...
Exception: Cannot find bean under name ...
Probable Cause: This is usually seen in association with a problematic Struts HTML SELECT custom tag. The Struts html:select tag behaves differently depending whether one or both of the name and property attributes is specified for its encompassed tags. If the name attribute is specified, whether or not if the property attribute is specified, then a bean matching the specified name will be expected in some scope (such as page, request, session, or application). If the matching bean is not found in any available scope, the error above will be seen.
There are two ways to address this. The first approach is to put a bean in one of the scopes so that the html:options might be associated with it. The second approach is to not specify the name attribute and instead use only the property attribute.



No getter method for property XXXX of bean org.apache.struts.taglib.html.BEAN
Exception: javax.servlet.jsp.JspException: No getter method for property username of bean org.apache.struts.taglib.html.BEAN
Probable Causes:
No getXXXX() method defined for form field with name XXXX.
This can happen if the JSP/Struts developer forgets that the name of the get method will have the same spelling as the value supplied in the Struts tag's property attribute, but that case will be different and is based on JavaBean specification rules. For example, my form class should have a getUsername method if my Struts form-related tag has username as the value for its property attribute. Note the difference in case marked with emphasis on the letter "U."
Related Links:
Case can trip up the matching between get method's name and name specified in Struts tag
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=58&t=000163



java.lang.NoClassDefFoundError: org/apache/struts/action/ActionForm
Exception: java.lang.NoClassDefFoundError: org/apache/struts/action/ActionForm
Probable Causes:
This error occurs typically when the specified Java .class file cannot be located in the classpath. If this occurs at runtime of a web application (error shows on browser rather than a rendered page), this typically means that specified class is not in the web server's classpath (made up primarily of /WEB-INF/classes and /WEB-INF/lib contents). Note that the NoClassDefFoundError in general typically indicates lack of the specified class in the relevant classpath. In this particular case the missing class would be ActionForm.class
This error is sometimes seen when one or more ActionForm.class instances are actually in the classpath. This most often occurs when ActionForm.class is made available correctly by placing struts.jar in the /WEB-INF/lib directory. When this library has been correctly placed and it is verified that ActionForm.class actually is present in the struts.jar file, the problem is either that more than one copy of ActionForm.class is in the classpath or (more likely) that duplicate versions of class files other than ActionForm are in the same classpath, causing confusion. This is especially true if a class that extends ActionForm is made available twice, such as in an .ear file that encompasses a .war file as well as in the .war file's own classpath (/WEB-INF/classes). This problem can be resolved by guaranteeing that there are no redundant classes, especially those related to Struts (directly from Struts or extensions of Struts), in the web application's view.
Related Links:


Exception creating bean of class org.apache.struts.action.ActionForm: {1}
Exception: javax.servlet.jsp.JspException: Exception creating bean of class org.apache.struts.action.ActionForm: {1}
Probable Causes:
Instantiating Struts-provided ActionForm class directly instead of instantiating a class derived off ActionForm. This might occur implicitly if you specify that a form-bean is this Struts ActionForm class rather than specifying a child of this class for the form-bean.
Not associating an ActionForm-descended class with an action can also lead to this error.


Cannot find ActionMappings or ActionFormBeans collection
Exception: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
Probable Causes:
Either the <servlet> tags for the Struts action servlet or the        <servlet-mapping> tags for the .do extension mapping        or both not present in the web.xml file.  I saw a case        where the web.xml file had no elements other than the root element        and so this error was occurring.
Typos or spelling errors in the struts-config.xml can lead to this error message. For example, missing a slash ("/") on a closing tag can have this effect.
Another element that must be present in the web.xml file is the load-on-startup element. This can be either an empty tag or can have an integer specified that indicates the priority of executing the associated servlet. The higher the number in the load-on-startup tags, the lower its priority.
Another possibility, related to need to use load-on-startup tag, is that precompiling JSPs using Struts can lead to this message as well.
Related Links: 
Explicitly Define <load-on-startup>
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=50&t=001055
http://threebit.net/tutorials/ejb/general/


NullPointerException at ... RequestUtils.forwardURL
Exception: java.lang.NullPointerException at org.apache.struts.util.RequestUtils.forwardURL(RequestUtils.java:1223)
Probable Causes: Missing path attribute in the forward subelement of the action element in struts-config.xml


Cannot find bean org.apache.struts.taglib.html.BEAN in any scope
Exception: javax.servlet.jsp.JspException: Cannot find bean org.apache.struts.taglib.html.BEAN in any scope.
Probable Causes: 
Trying to use Struts form subelement tags outside of the Struts' form tag. Note that this might be because you are using the Struts html tags after the closing tag.
Note that if you accidentaly make your opening html:form tag a no-body tag (you put a closing / at the end so that it looks something like ), this may be treated by your web server's parser as a no-body tag and everything after that tag you meant to be an opening tag will be outside of the form tag by default.
Note your prefix may be different than html, but most people seem to use that as their prefix for the Struts HTML tags library.

Related Links:
Using form subelements outside of a form tag
http://forum.java.sun.com/thread.jsp?thread=337537&forum=4&message=1384153 


Missing message for key xx.xx.xx
Exception: javax.servlet.jsp.JspException: Missing message for key xx.xx.xx
Probable Causes:
The key-value pair with specified key is not in ApplicationResources.properties file.
ApplicationResources.properties file not in classpath (not in WEB-INF/classes directory in specified location)


Cannot find message resources under key org.apache.struts.action.MESSAGE
Exception: Cannot find message resources under key org.apache.struts.action.MESSAGE
Probable Causes:
Explicitly trying to use message resources that are not available (such as ApplicationResources.properties not available.
Implicitly trying to use message resources that are not available (such as using empty html:options tag instead of specifying the options in its body -- this assumes options are specified in ApplicationResources.properties file).
XML parser issues -- too many, too few, incorrect/incompatible versions.
Related Links:


No input attribute for mapping path /loginAction
Exception: No input attribute for mapping path /xxxxAction
Probable Causes: No input attribute in action mapping in struts-config.xml file for the action with the name specified in the error message. An input attribute is not required if form validation is not performed (either because the validate attribute is set to false or because the validation method in the relevant form class is not implemented. The input attribute specifies the page leading to this action because that page is used to display error messages from the form validation.


Strange Output Characters
Exception: Strange and seemingly random characters in HTML and on screen, but not in original JSP or servlet.
Probable Causes: 
Regular HTML form tags intermixed incorrectly with Struts html:form tags.
Encoding style used does not support characters used in page.


"Document contained no data" or no data rendered on page
Exception:
"Document contained no data" in Netscape
No data rendered (completely empty) page in Microsoft Internet Explorer
Probable Cause: Employing a descendent of the Action class that does not implement the perform() method while using the Struts 1.0 libraries. Struts 1.1 Action child classes started using execute() rather than perform(), but is backwards compatible and supports the perform() method. However, if you write an Action-descended class for Struts 1.1 with an execute() method and try to run it in Struts 1.0, you will get this "Document contained no data" error message in Netscape or a completely empty (no HTML whatsoever) page rendered in Microsoft Internet Explorer.

Saturday, June 28, 2008

Struts: Upload file using Struts and Generates unique ID for file name

Delicious 0
Someone finding the way to upload file with struts, it's simple...You only create form with Struts: Form class with file property is FormFile. But,..how to upload file to server with unique name in folder if some file has same name ???. Now, with this post, you'll resolve it, very simple!!!.

First, simply create your Struts form class, below is UploadFileForm, class extends ValidatorActionForm because i want to validate Form for uploading, class:

package prlamnguyen.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.validator.ValidatorActionForm;

/**
* Upload File Form Class.
*
* @author prlamnguyen
* @link http://prlamnguyen.blogspot.com/2008/06/upload-file-using-struts-and-generates.html
*/

public class UploadFileForm extends ValidatorActionForm {


   /*
   * Extends ValidatorActionForm if you want to validate form
   */

   /** image property */
   private String fileName;


   /** fileImage property */
   private FormFile file


   /**
   * @return the file
   */
   public FormFile getFile() {
      return file;
   }


   /**
   * @return the fileName
   */
   public String getFileName() {
      return fileName;
   }


   /**
   * @param file the file to set
   */
   public void setFileImage(FormFile file){
      this.file = file;
   }


   /**
   * @param fileName the fileName to set
   */
   public void setImage(String fileName) {
      this.fileName = fileName;
   }


   /**
   * Method validate
   * @param mapping
   * @param request
   * @return ActionErrors
   */
   public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
      // Validate your form if you want
      // This helpful for validate type of file, size, extension of file ....
      return null;
   }


   /**
   * Method reset
   * @param mapping
   * @param request
   */
   public void reset(ActionMapping mapping, HttpServletRequest request) {
      // Reset your form input
   }

}




Above is UploadFileForm class, we have 2 properties: (String) fileName and (FormFile)file , with property file, you must import org.apache.struts.upload.FormFile which is struts capabilities, with MyEclipse 3.x or above, you can do that simply.

Now, we must create action class for struts, name of action class is UploadFileAction:



package prlamnguyen.struts.action;


import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import prlamnguyen.struts.form.UploadFileForm;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;


/**
* Creation date: 05-31-2008
*
* Upload File Action Class.
*
* @author prlamnguyen
* @link http://prlamnguyen.blogspot.com/2008/06/upload-file-using-struts-and-generates.html
*
* Definition:
* @struts.action path="/uploadFile" name="uploadFileForm" input="/upload_file.jsp" scope="request" validate="true"
* @struts.action-forward name="failed" path="/upload_file.jsp"
* @struts.action-forward name="success" path="/upload_successful.jsp"
*/
public class UploadFileAction extends Action {
   /*
   * Generated Methods
   */



   /**
   *
   * @param uploadForm
   * @return
   */
   public String uploadFile(UploadFileForm uploadForm) {
      // Process the FormFile
      FormFile myFile = uploadForm.getFile();
      String fileName="default";
      // Get the file name
      try {
          // Precreate an unique file and then write the InputStream of the uploaded file to it.
          File uniqueFile = DoFile.uniqueFile(new File("your file patch"), myFile.getFileName());
          DoFile.write(uniqueFile, myFile.getInputStream());
          fileName = uniqueFile.getName();

          // Show succes message.
          System.out.println("Upload file complete");

      } catch (IOException e) {

          // Show error message.
          System.out.println("Upload file failed");

          // Always log stacktraces.
          e.printStackTrace();
      }
      return fileName;
   }

   /**
   * Method execute
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   */
   public ActionForward execute(ActionMapping mapping, ActionForm form,
       HttpServletRequest request, HttpServletResponse response) {
       UploadFileForm uploadForm = (UploadFileForm) form;
       // to do execute
       ActionForward forward = new ActionForward();

       image = uploadImage(uploadForm);


       return forward = mapping.findForward("success");
   }
}




Ukie, all important thing done, DoFile above is one class file you must declare, and Struts must be config-ed:


  • DoFile Class:

/**
* Generate unique file based on the given path and name. If the file exists, then it will
* add "[i]" to the file name as long as the file exists. The value of i can be between
* 0 and 2147483647 (the value of Integer.MAX_VALUE).
* @param filePath The path of the unique file.
* @param fileName The name of the unique file.
* @return The unique file.
* @throws IOException If unique file cannot be generated, this can be caused if all file
* names are already in use. You may consider another filename instead.
*/
public static File uniqueFile(File filePath, String fileName) throws IOException {
   File file = new File(filePath, fileName);
   if (file.exists()) {
        // Split filename and add braces, e.g. "name.ext" --> "name[", "].ext".

        String prefix;
        String suffix;
        int dotIndex = fileName.lastIndexOf(".");


       if (dotIndex > -1) {
            prefix = fileName.substring(0, dotIndex) + "[";
            suffix = "]" + fileName.substring(dotIndex);
        } else {
            prefix = fileName + "[";
            suffix = "]";
        }
       int count = 0;
        // Add counter to filename as long as file exists.

       while (file.exists()) {

          if (count < 0) { // int++ restarts at -2147483648 after 2147483647.
             throw new IOException("No unique filename available for " + fileName
                                   + " in path " + filePath.getPath() + ".");
           }
           // Glue counter between prefix and suffix, e.g. "name[" + count + "].ext".
           file = new File(filePath, prefix + (count++) + suffix);

        }
   }

   return file;
}

/**
* Write byte inputstream to file. If file already exists, it will be overwritten.It's highly
* recommended to feed the inputstream as BufferedInputStream or ByteArrayInputStream as those
* are been automatically buffered.
* @param file The file where the given byte inputstream have to be written to.
* @param input The byte inputstream which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, InputStream input) throws IOException {
   write(file, input, false);
}






<form-beans >
  <form-bean name="UploadFileForm" type="prlamnguyen.struts.form.UploadFileForm" />
</form-beans>

<action-mappings >
<action
attribute="uploadForm"
    input="/upload_file.jsp"
    name="uploadFileForm"
    path="/uploadFile"
    scope="request"
    type="prlamnguyen.struts.action.UploadFileAction">
    <forward name="failed" path="/upload_file.jsp" />
    <forward name="success" path="/upload_successful.jsp" />
</action>
</action-mappings>



Done, finish is create new JSP page and create Struts Form JSP, to upload your file, form with property: file.

Now, use any edit program, create new jsp file, here i create upload_file.jsp (for input and forward failed) :

<html:form action="/uploadFile" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
 <tr>
   <td class="spectd">Chose file to upload: </td>
   <td><html:file property="file"/> <html:errors property="file"/></td>
 </tr>
</table>
<div align="center">
 <html:submit/>&nbsp;&nbsp;<html:reset/>
</div>
</html:form>


Note: you must have enctype="multipart/form-data" to send request upload file to server.

You should create successful page to print out when upload successful. In struts config, i created config-forward "success" with upload_successful.jsp jsp page.

If you done everything above, all classes were created, build all and deploy into your server and testing from url: http://localhost:8080/UploadFile/upload_file.jsp.

All wrong please email prlam.nguyen@gmail.com or comment here.
Regard!


© 2008, Lam Duy Nguyen

Friday, February 02, 2007

Struts: Validate form with Struts Validation

Delicious 0
When using Struts, you can easily validate datas before excute. So many way to validate the form with Struts, you can use JavaScripts, XML validator...many, many way to validate them...This article is not a new way for this, but it's simple to use if you're not sure about use javascript or other way.

Before use validating, you must sure that you can create the Struts form. If not, read following article, it's a tutorial how to Create Basic Struts Form.

First, you have to understand that Struts Validation will only work if your form-bean extends org.apache.struts.validator.ValidatorActionForm. So, your form which be validated, will looks like:



public class ExampleForm extends ValidatorActionForm {

    ...

}


Following lines belows are code of form-bean in this aticle:




package prlamnguyen.struts.form;

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


/**
* @author Nguyen, Lam Duy
* @link http://prlamnguyen.blogspot.com/2007/02/java-tutorial-validate-form-with-struts.html
*/

/**
* Form bean for the Struts Validation Example.
*
*/
public class ExampleForm extends ValidatorActionForm
{
   private String name=null;
   private String emailAddress=null;

   public void setName(String name){
      this.name=name;
   }

   public String getName(){
      return this.name;
   }


   public void setEmailAddress(String emailAddress){
      this.emailAddress=emailAddress;
   }

   public String getEmailAddress(){
      return this.emailAddress;
   }


   /**
   * Reset all properties to their default values.
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   */
   public void reset(ActionMapping mapping, HttpServletRequest request) {
      this.name=null;
      this.emailAddress=null;
   }

   /**
   * Validate form input before excuted.
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   * @return errors
   */
   public ActionErrors validate( 
       ActionMapping mapping, HttpServletRequest request ) {
       ActionErrors errors = new ActionErrors();

      if( getName() == null || getName().length() < 1 ) {
          errors.add("name",new ActionMessage("error.name.required"));
       }
      if( getEmailAddress() == null || getEmailAddress().length() < 1 ) {
          errors.add("emailaddress",new ActionMessage("error.emailAddress.required"));
       }

      return errors;
   }

}




The above class populates the Example Form data and validates it. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. In Struts 1, ActionError seem to be deprecated and will be removed in Struts 2, so, i'm now using ActionMessage in this article. Ok, for the next, you must create a new Action class for Struts, because of form-bean's name is ExampleForm, Action class must be named as ExampleAction and extends org.apache.struts.action.Action. Form-bean above is Model of web struts application and the action class is Controller. I'll not guide to create an Action class, the previous post, i had created one, see here, config Struts is so easy and it was posted in that post.



Application Resources



An importance when using Struts to validate form is display error messages. Ignore everything about Controller and Struts Config, i'll explaint how to display error messages. First, you have to create ApplicationResources file in Struts Package, in my post, i packaged my model as "prlamnguyen.struts.form", so ApplicationResources will be in "prlamnguyen.struts" with name ApplicationResources.properties.






  • ApplicationResources.properties
# Resources for parameter 'prlamnguyen.struts.ApplicationResources'

# Project Example Struts Validation
# This will appear before each individual error.

errors.prefix=<span class="errors">

# This will appear after each individual error.

errors.suffix=</span><br />
errors.name.required=Name is required.

errors.emailAddress.required=Email Address is required.
Now, create a jsp file to input data. Note, when displaying error messages in jsp page, you can display individual or group error messages. If individual, add property value for each <html:errors /> else if group errors, only thing to do is adding <html:errors /> to anywhere you want to display error messages.


  • Individual
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>


<html> 
<head>
<title>JSP for ExampleForm form</title>
</head>
<body>
   <html:form action="/example">
      Name : <html:text property="name"/><html:errors property="name"/><br/>
      Email Address : <html:text property="emailAddress"/><html:errors property="emailAddress"/><br/>
      <html:submit/><html:cancel/>
   </html:form>
</body>
</html>
  • Group
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html> 
<head>
<title>JSP for ExampleForm form</title>
</head>
<body>
   <html:errors />

   <html:form action="/example">
      Name : <html:text property="name"/><br/>
      Email Address : <html:text property="emailAddress"/><br/>
      <html:submit/><html:cancel/>
   </html:form>
</body>
</html>
Deploy your project and test with example URL: http://localhost:8080/WebTutorial/form/example.jsp





Screen when do nothing is:




Screen when validate() method was excuted




and Group Error Messages




Validation in Struts is so easy, right ^^ ?

Wednesday, January 31, 2007

Struts: The basic Web Struts Application

Delicious 0
Before read this article, be sure you know What is the Strusts Framework?
So, this article will explaint how to build an simple Web Struts Application?. It have many program support easily-build-int
Struts such as: MyEclipse, NetBean ... But, the basic guide for building Struts is very helpful for new to Struts and Java programming. This example will help you understand Struts in detail. I'll create new user interface to accept Name and Email address from user-input. In this case, form input was create with a basic JSP template called input.jsp and the success page will be success.jsp. Action class is just forwarding it to the sucess.jsp.

Action Form for struts (MODEL).



So, what's ActionForm? It's JavaBean that extends org.apache.struts.action.ActionForm. This bean will be maintains the session state for web application, data input from form at client-side will be automatically added as the object in server-side. In this case, i'll create new ActionForm name as GuestForm.java

  • GuestForm.java
package prlamnguyen.struts.form;

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


/**
* @author Nguyen, Lam Duy
* @link http://prlamnguyen.blogspot.com/2007/02/java-tutorial-basic-web-struts.html
*/

/**
 * Form bean for the Guest entry.
 *
*/
public class GuestForm extends ActionForm
{
  private String name=null;
  private String emailAddress=null;

  public void setName(String name){
    this.name=name;
  }

  public String getName(){
    return this.name;
  }

  public void setEmailAddress(String emailAddress){
    this.emailAddress=emailAddress;
  }

  public String getEmailAddress(){
    return this.emailAddress;
  }


  /**
   * Reset method will be used for reseting all data to default is null.
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   */
  public void reset(ActionMapping mapping, HttpServletRequest request) {
     this.name=null;
     this.emailAddress=null;
  }

  /**
   * Validate method to vailde the data inputed from form at client-side. It's be
   * excute at Server-side. Set return to null if you not want to validate the
   * form input
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   * @return errors
   */
  public ActionErrors validate(
      ActionMapping mapping, HttpServletRequest request ) {
      //In this case, i'll not validate form, i want this article simply
       //The validate form for struts will be posted later.
      return null;
  }

}

Action Class for Struts (Controller)


Next step, create Action class, Action class is a Controller which receives the request, looks up the mapping for this request, and forwards it to an action. I'll create new class file name GuestAction.java which simply forward the request the success.jsp.

  • GuestAction.java
package prlamnguyen.struts.action;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;



/**
* @author Nguyen, Lam Duy
* @link http://prlamnguyen.blogspot.com/2007/02/java-tutorial-basic-web-struts.html
*/

public class AddressAction extends Action
{
  /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  * @throws Exception
  */
  public ActionForward execute(ActionMapping mapping, ActionForm form,
                    HttpServletRequest request, HttpServletResponse response) throws Exception{
       ActionForward forward = new ActionForward();
       forward = mapping.findForward("success");
      return forward;
  }
}
Now, create config file for Struts, default name for struts config file is struts-config.xml. Add the following lines in the struts-config.xml file:

  • struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
                                             "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>



 ...


 <!--
Define form-bean class.
-->

 <form-beans >
 <form-bean name="guestForm" type="prlamnguyen.struts.form.GuestForm" />
</form-beans>


 ...

 <action-mappings >

 <!--
These line below for handling the action "/guestInput.do".
-->
  <action
     attribute="guestForm"
     input="/input.jsp"
     name="guestForm"
     path="/guestInput"
     scope="request"
     validate="false"
     type="prlamnguyen.struts.action.GuestAction">

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

 ...

 </struts-config>


The action *.do have to define in web.xml. Add following code into web.xml file. This step can be ignored when you use MyEclipse or NetBean ... to add Struts. In this case, i'll do it for you.


  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
          http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">




 ...


 <!--
Add these line for using struts in web application, 
    default code can be generated by other program such as: MyEclipse, NetBean....
-->
  <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>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>


 ...


  <servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


 ...


 </web-app>
JSP for input and Display (VIEW).

Last, create the new jsp page for form input which is our form for entering the details and jsp page for success message, in Struts Config, input-form file was defined as input.jsp and success page is success.jsp.

  • input.jsp
<html:form action="/guestInput">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Name:</td>
<td><html:text property="name"/></td>
</tr>
<tr>
<td>Email Address:</td>
<td><html:text property="emailAddress"/></td>
</tr>
</table>
<div align="center"> 
<html:submit/>&nbsp;&nbsp;<html:reset/>
</div>
</html:form>  
  • success.jsp
  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Success</title>
</head>
<body>
       Input successful !

 </body>
 </html>  
Correct me if I'm wrong.

Regard!


© Nguyen, Duy Lam 2008

Sunday, December 31, 2006

What Is the Struts Framework?

Delicious 0

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

  • Open source
  • Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
    • Model: application state
    • View: presentation of data (JSP, HTML)
    • Controller: routing of the application flow
  • Implements the JSP Model 2 Architecture
  • Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.

Architecture Overview



All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:

From View to ActionA user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function.
From Action to ViewAfter the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser.

The diagram below describes the flow in more detail:


  1. User clicks on a link in an HTML page.
  2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.
  3. Action makes a call to a Model layer service.
  4. Service makes a call to the Data layer (database) and the requested data is returned.
  5. Service returns to the action.
  6. Action forwards to a View resource (JSP page)
  7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
  8. JSP file is invoked and sent to the browser as HTML.
  9. User is presented with a new HTML page in a web browser.

Struts Components

The Controller

This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.

The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.

Action Classes

It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.

View Resources

View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.

ActionForms

These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

Model Components

The Struts Framework has no built-in support for the Model layer. Struts supports any model components:

  • JavaBeans
  • EJB
  • CORBA
  • JDO
  • any other

by Exadel