This example shows the basic login application demo using Struts2.
The necessary libraries are shown below,
The first important setting is FilterDispatcher configuration in web.xml
Next we need to configure struts.xml with action url path and associated java action class.
By default struts2 executes public String execute() method as action method and the return string
is used to identify the result. Here we have specified two results namely 'success' which forwards
to '/success.jsp' and 'failure' which forwards to '/failure.jsp'. The struts.xml file
has to be in class path.
public void setPwd(String pwd) { this.pwd = pwd;
}
public String getUser() { return user;
}
public void setUser(String user) { this.user = user;
} public String execute(){ if(user.equals(pwd)){ return "success";
} return "failure";
}
}
We can observe that user and pwd field are not
initialized with values from request using request.getParameter("fieldName") in action class
and the action is just a POJO. Strut2 simplifies this task with 'Parameter Interceptors'.
It automatically binds the user entered values with action properties.
We can observe that the name of textfield and password field matches with properties in 'Login' class.
Struts2 provides a tab library which simplifies the page rendering. On clicking the submit
button it gets submitted to http://localhost:8080/Login/demo/login.action
assuming you are using Tomact with default port configuration.
The login page is shown below,