Monday, May 24, 2010

Strut2-String Validation


Struts 2 – String Validation


Aim:

            It is very important one to validate user input when we are going to create the web project. So we will learn how to validate the user input such as String , integer, Email etc,.

Procedure:

            Step_1:

                        Create ActionSupport

                       Create Folder example under source packages(if it dose not).

                       If it is, we use already created Folder example.

                        Right click on example

New Other under categories Struts2 and under File types Struts2 Action.

Next where you give class name and click Finish.


Include following coding into the action support

package example;
import com.opensymphony.xwork2.ActionSupport;

public class StringVaLidationAction extends ActionSupport{

  private String username;

  public String execute() throws Exception
  {
    if (getUsername() != null)
    {
      return SUCCESS;
    }
    else
    {
      return ERROR;
    }
  }

  public void setUsername(String username)
  {
    this.username = username;
  }
  public String getUsername()
  {
    return username;
  }
}



Step_2:

Create jsp file

Create Folder example under web pages

Right click on example . New other web jsp you give jsp name ( I have used jsp name as stringInputForm.jsp.

< %@ taglib prefix="s" uri="/struts-tags" % >

< html >

< head >
< title > Input form < /title >
< s:head/ >
< /head >

< body >

< s:form method="POST" action="stringValidation" >

< s:textfield label="Enter User Number" name="username" maxlength="10" / >

< s:submit / >
< /s:form >

< /body >

< /html >


Step_3:

Create stringSuccess.jsp

Include following code into the string Success.jsp

< %@page language="java" %>
< html >

< head >
< title > Correct entry < /title >
< /head >

< body >
< b > Welcome to < /b > < %=request.getParameter("username") % > !
< /body >

< /html >


Step_4:

Made come changes in struts.xml.

Source package
|
|
< default package >
|
|
struts.xml

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

< struts >

< package name="example" namespace="/example" extends="struts-default" >

< action name="stringValidation" class="example.StringVaLidationAction" >

< result name="input" > /example/stringInputForm.jsp < /result >
< result name="error" > /example/stringInputForm.jsp < /result >
< result name="success" > /example/stringSuccess.jsp < /result >
< /action >

< /package >

< /struts >









Step_5:


Structure of the application


Step_6:

Run stringInputForm.jsp

Right click on stringInputForm.jsp

Conclusion:


From this post we have learnt how to validate String input. You have any doubt, you will post comments.


No comments:

Post a Comment