Forms and FormBean Interactions

Forms and FormBean Interactions

Previous Home Next

 

In this section We cover Forms and FormBean Interactions.FormBean class is a simple java bean class that extends ActionForm class. This class have getter and setter method.

 
The following is example of Form .This is created by  using HTML tag library.The data of this form will gather into ActionForm class .

Example :-

index.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<html:form action="/login" >
<table  border="1" bordercolor="red">
<tr> <td align="center" height="50px" style="background: gray;">
Login Example in Struts 1.3</td> </tr>
<tr><td align="center" width="250px" height="150px" style="background: gray;">
<table>
<tr> <td>User Name</td> 
<td><html:text name="loginForm" property="name"/></td> </tr> 
<tr> <td>Password</td> 
<td> <html:password name="loginForm" property="password"/></td> </tr>
 <tr> <td colspan="2" align="right">
<html:submit value="login"/></td> </tr>
</table></td></tr>
</table>
</html:form>
</body>
</html>

Here action="/login" is URI to lookup in struts-config.xml file to where all data will gather in appropriate  ActionForm.

We client request for this page then page will coveted into HTML tags with action="/login.do".

When cleint click on submit button then controller will call appropriate ActionForm on the behalf of  value of "action".

Create a login form bean  :-

LoginForm.java

package com.r4r;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class LoginForm extends org.apache.struts.action.ActionForm{
private static final long serialVersionUID = 11112;	
private String username;
private String password;	

public String getPassword() {	
return password;	}
public void setPassword(String password) {		
this.password = password;	}	
public String getUsername() {	
return username;	}	
public void setUsername(String username) {		
this.username = username;	}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();	
if (username == null || username.length() < 1) {	
errors.add("username", new ActionMessage("error.username.required"));		}
else if (password == null || password.length() < 1) {	
errors.add("password", new ActionMessage("error.password.required"));	
}return errors;
}
}

Output




Previous Home Next