Struts2 Validation using annotation
Problem:
Create Login page with validation and using annotation.
Procedure:
You have known how to create project for struts2 using Netbean6.8.
Step 1:
Create project name as AnnotationPro
Step 2:
Create LoginAction
Add following coding into LoginAction.java
package example;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validation;
@Validation
public class LoginAction extends ActionSupport
{
private String username;
private String password;
@RequiredStringValidator(message="Supply Password")
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
@RequiredStringValidator(message="Supply Username")
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public LoginAction()
{
}
public String execute() throws Exception
{
if((getUsername().equals("suresh"))&&(getPassword().equals("kumar")))
{
return "success";
}
else
{
return "error";
}
}
}
Step 3:
Create home.jsp
< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< title > Hom Page < /title >
< /head >
< body >
< s:form action="LoginAction" method="post" >
< s:actionerror/ >
< s:fielderror/ >
< s:textfield label="UserName" name="username"/ >
< s:password label="PassWord" name="password"/ >
< s:submit value="Login"/ >
< /s:form >
< /body >
< /html >
Step 4:
Create success.jsp
< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< title > Hom Page < /title >
< /head >
< body >
< h1 > Hello World! < /h1 > you are valid
< /body >
< /html >
Step 5:
Made some changes in struts.xml
< !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" extends="struts-default" >
< action name="LoginAction" class="example.LoginAction" >
< result name="input" > /example/home.jsp < /result >
< result name="error" > /example/home.jsp < /result >
< result name="success" > /example/success.jsp < /result >
< /action >
< /package >
< /struts >
Step 6:
Run the home.jsp
You give username as suresh and password as kumar
The success.jsp file will display.
You don’t give username
you don’t give password