Struts Validation Client Side and Server Side

download Struts Validation Client Side and Server Side

of 12

Transcript of Struts Validation Client Side and Server Side

  • 7/30/2019 Struts Validation Client Side and Server Side

    1/12

    Struts Validation (Client and Server Side)

    Before We StartIn this tutorial we will show you how to use the Struts Validation Framework. This frameworkis very powerful but at the same time can be very complex. Even implementing a simplevalidation, for example, checking if a value was entered, can be a tedious task. However,we are not going to get into any complex theory behind Struts validation. There are plenty ofbooks that do that. But, we will show you how to add simple validation to your applicationand hopefully you will be able to take it from there.

    For this tutorial, we are again going to continue working with ourguessGame application. Ifyou already have it, great; if not,download it, unzip it in the Eclipse project directory, andimport it into Struts Studio. Now, we are ready to start!

    Adding Validation to the ProjectOur first step will be to create the validation itself. Once we have it ready, we can choose ifwe want to use client or server side validation. To switch from one approach to anotherrequires very minor changes. In this tutorial we will show both ways.

    To proceed, we will first add the ValidatorPlugIn to struts-config.xml file. Then, open aneditor for the struts-config.xml file and switch to the Tree view. Now, right-click plug-ins and select Create Special Plug-in/Validators. This will add two XML validation files toyour project. If you look at the source, you should see the plug-in that we just added at thebottom. This tells the Struts runtime where to look for your validation definitions.

    Next, we need to create a properties file with default error messages. Right

    click JavaSource/sample and select New/New Properties File. Call thefile applResorces.

    Next, we need to add this file to our application. Switch to the Tree view ofstruts-config.xml. Right-click resources/Define Message Resource... . We only need to supplythe first field. Click the Change button for the parameter field and browseto guessGame/sample/applResources.properties. Select the file and click Ok and thenFinish. We have now added the properties file to our application.

    There is one last step before we start with the actual validation. Right-click sample.applResources and select Add Default Error Messages. After this, save allchanges in the project. We are now ready to define our actual validation rules.

    Before this, let's run our application just once to see what validation we want to add. Start

    Tomcat server. Then switch to the Diagram view of the struts-config.xml file and right-clickthe start Forward and select Run.

    Creating Validation RulesWe will add two validation rules to our application. First, we'll make sure that some inputwas entered. Second, we'll make sure that the value entered is an integer and is between 0and 100.

    http://www.exadel.com/tutorial/struts/5.2/guess/jar/guessGame.jarhttp://www.exadel.com/tutorial/struts/5.2/guess/jar/guessGame.jarhttp://www.exadel.com/tutorial/struts/5.2/guess/jar/guessGame.jarhttp://www.exadel.com/tutorial/struts/5.2/guess/jar/guessGame.jar
  • 7/30/2019 Struts Validation Client Side and Server Side

    2/12

    Locate and open the WebContent/WEB-INF/validation.xml file (make sure you open itwith the default editor, the Struts Studio XML Editor). You should now see the Struts StudioValidation editor. This visual editor allows you to define validation rules instead of typingXML code manually in the struts-config.xml file.

    Right-click formset(default) and select Create Form. This will be the Form bean

    (ActionForm) that captures input from the JSP page. Type in "MakeGuessForm" andclick Finish.

    Now, right-click MakeGuessForm and select Create Field. We now need to create the fieldthat we want to validate. Type in "guessNumber" and click Finish. Your editor should looklike the image below.

    The next step is to create validation rules. Right-click guessNumberand select AddValidation Rule. This screen allows us to add validation rules. Note that validation rules aretaken from the validation-rules.xml file. You could, of course, create your own validationrules and then simply select your validation file.

    Select required from the left pane and click the Add-> button. This rule will make sure thata user enters something on the web page.

  • 7/30/2019 Struts Validation Client Side and Server Side

    3/12

    Click Ok. Now we need to create what we want to display when the users enters nothing.

    Select required underguessNumberand click Add in the middle window ( Arg -Replacement Value for Message Template). Don't worry if you don't yet understand whatis happening. It all should become more clearer as we progress.

    All values will stay the same. We just need to enter something forKey. Click Change....

    You should now see ourapplResources file and the default error messages that we haveadded. We will create a new key for this validation rule.

    Click Add and create the property described below, click Finish when done.

    name value

    Name input.required

    Value Input number

    The new entry should now appear in the list. Go ahead and click Ok to exit from this screen.We should be back at this screen.

  • 7/30/2019 Struts Validation Client Side and Server Side

    4/12

    Let's see what we have here.

    name value description

    Name required Name of the validation rule that we selected from a list of available rules to use(from validation-rules.xml). This validation rule has the following error message: {0}is required.

    Arg arg0 This will be replaced with the value of key below during runtime. In other words, theerror message has the following form {0} is required and so arg0 will be looked up viathe input.required key and its value will be inserted instead of{0}.

    Key input.required This is the key to look up the message to replace {0}.

    Resource true This is where to look for a replacement message. If true, look inside the resource file.

    Now, save all changes.

    So, we have created our first validation rule. We'll go ahead and start with client-sidevalidation and see how it works. We'll make some minor changes to our JSP files and runthe application.

    Open the/pages/start.jsp page. Only two minor changes are required. Add the followingright after the tag:

  • 7/30/2019 Struts Validation Client Side and Server Side

    5/12

    and then modify this line (changes in blue):

    That's all that needs to be done to the JSP page to add client-side validation. We alsohave/pages/nomatch.jsp, go ahead and make the same changes to that page.

    That's it. We're ready to run the application. First, save all changes. Recompile the wholeproject, during compilation applResources will be copied to classes folder so that runtimecan find it. Restart Tomcat server.

    Launch the application in a web browser. Go ahead and hit Guess without enteringanything. You should see the error message below.

    Adding a Second Validation Rule

  • 7/30/2019 Struts Validation Client Side and Server Side

    6/12

    We are ready to add another validation rule. This rule will check if the value entered isbetween 0 and 100. It will also check if the value entered is an integer.

    Go ahead and open the validation.xml file in the Formsets view as shown below.

    Right-click guessNumberand select Add Validation Rule.

    Scroll down in the left pane and select the intRange rule and add it to the right pane.Click Ok when done. So now we have two rules.

    In the middle pane (Arg - Replacement Value for Message Template) click Add.Select Change.... The intRange validation rule uses this message template: {0} is not inthe range {1} through {2}.

    Now, we need three replacement values for each of the {} arguments. The {0} should be thename of the field and {1} and {2} should tell us the range.

    So for, {0} we will use an existing message. Go ahead and select input.required. In otherwords, {0} will be replaced by Input number. Click Ok twice to exit.

    Now we need values for {1} and {2}. Click Add again in the middle pane. We are going toadd another argument but this time it will not be taken from the resource file. We will createa Validator Parameter as the replacement value for{1}.

    Enter the following values:

    name value description

    Name intRange Name of the validation rule that we selected from a list of available rules to use(from validation-rules.xml).

  • 7/30/2019 Struts Validation Client Side and Server Side

    7/12

    Arg arg1 This will be replaced by lower range limit.

    Key ${var:min} This tells to look for replacement value in the vars.

    Resource false We are not going to look for replacement value in the resource file.

    Click Ok when done. We now need to add another arg forarg{2}. Click Add again andcreate this entry:

    name value description

    Name intRange Name of the validation rule that we selected from a list of available rules to use(from validation-rules.xml).

    Arg arg2 This will be replaced by the upper range limit.

    Key ${var:max} This tells us to look for a replacement value in the vars.

    Resource false We are not going to look for replacement value in the resource file.

    Click Ok when done. Now we have our three arguments that are going to replace { } duringruntime. We are not done yet, because we still need to define ${var:min} and ${var:max}.

  • 7/30/2019 Struts Validation Client Side and Server Side

    8/12

    Click Add in the lower pane (Var - Validator Parameter). This is where we are going todefine ourmin and max var values. Create the following two entries:

    name value

    Var-name min

    Var-value 0

    And this one:

    name value

    Var-name max

    Var-value 100

  • 7/30/2019 Struts Validation Client Side and Server Side

    9/12

    After you create these Validator Parameters, you should have this view.

    We are actually done. Save all changes, recompile the whole project and restart Tomcatserver.

  • 7/30/2019 Struts Validation Client Side and Server Side

    10/12

    Now hit Guess without entering anything. You should see the first error message. Enter avalue that is not in the range, for example -5. You should get this error.

    Please note that we have only modified one of the JSP files, start.jsp. You need tomodify nomatch.jsp as well to have client side validation on that page.

    Using Server-Side ValidationTo use server side validation instead of client side we only need to make some minorchanges because we are still going to use the same validation rules that we alreadycreated.

    We first need to modify the start.jsp file. First delete the part in blue, becuase we are notgoing to be calling JavaScript anymore. Instead, we are going to be sending the request tothe server and validate our input there.

    you should have this left:

    Now, add this line right before tag (in blue):

    ...


  • 7/30/2019 Struts Validation Client Side and Server Side

    11/12

    ...

    We are done making changes to this JSP page. Save all changes. The last thing that weneed to do is to make some minor changes to the MakeGuessForm.java file.Open MakeGuessForm.java and make the following changes.

    First, comment out the validate() method.

    ...

    /***

    public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest request)

    {

    return null;

    }

    ***/

    ...

    and, second, modify the base class that our form extends, as shown below in blue.

    ...

    public class MakeGuessForm extends org.apache.struts.validator.ValidatorForm

    ...

    The last thing that we need to do is to modify properties for our Action. On the Web Flowdiagram, right-click the/makeGuess Action and select Properties. For the input property,

    click at the end of the value field to open a browse editor.In the Pages tab, browse to guessGame/WEB-ROOT/pages/start.jsp. Click Ok.The input parameter tells Struts runtime where to go if validation fails, in other words if anerror has occurred. In our example, we are going back to the same page to show the errormessage. Click Close.

    We are done. Save all changes. Recompile the whole project and restart Tomcat server. Goahead and run the application in a web browser. Enter a negative value, for example -9.

  • 7/30/2019 Struts Validation Client Side and Server Side

    12/12

    You should see the following page.