Friday, 29 April 2011

Struts Class 8



Now we have a requirement like we wanted to validate the form fields
How to validate?
By overriding the following behaviour 


ActionErrors validate(ActionMapping am,HttpServletrequest req)


Another requirement is our application should support i18n(Internationalization).


with respect to struts framework we are given with predefined bean tags 
<bean:message>






Do the modifications in the previous example


1. Login.jsp





<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<body>
<html:form action="login.stech"><pre>
<bean:message key="uname"/><html:text property="uname"/>
<html:errors property="uname"/>
<bean:message key="pass"/><html:password property="pass"/>
<html:errors property="pass"/>
<html:submit>
<bean:message key="submit"/>
</html:submit>
</pre>
</html:form>
</body>
</html>





In LoginActionForm.java




package com.cg.struts.form;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class LoginActionForm extends ActionForm
{
public void setUname(String uname){this.uname=uname;}
public String getUname(){return this.uname;}
public void setPass(String pass){this.pass=pass;}
public String getPass(){return this.pass;}
public ActionErrors validate(ActionMapping am,HttpServletRequest req)
{
//first instantiate ActionErrors
ActionErrors ae=new ActionErrors();
//using control flow statements
if(getUname().equals(""))
{
//add to the ActionErrors
ae.add("uname",new ActionMessage("field.required","UserName"));
}
else if(getUname().length()<3)
{
ae.add("uname",new ActionMessage("minlengthrequired"));
}
if(getPass().equals(""))
{
ae.add("pass",new ActionMessage("passrequired"));
}
//check the size of ActionErrors object
if(ae.size()==0)
{
return null;
}
return ae;
}
String uname,pass;
};


3) Inside the classes folder Save the following file

ApplicationResources.properties


uname=UserName
pass=Password
submit=Login
field.required=Please give {0}
minlengthrequired=UserName should have min3 characters.
passrequired=You did not give password


4)In struts-config.xml file



<struts-config>
<form-beans>
<form-bean name="mybean" type="com.cg.struts.form.LoginActionForm"/>
</form-beans>
<action-mappings>
<action type="com.cg.struts.action.LoginAction" path="/login" name="mybean" input="/Login.jsp" validate="true">
<forward name="success" path="/Welcome.jsp"/>
<forward name="fail" path="/Login.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
</struts-config>




Deploy this application in Tomcat web apps folder.










No comments:

Post a Comment