Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

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