CHAPTER 4: Building a Web Application Using Struts 2 167
//getters and setters
// ...
public String execute() {
return "SUCCESS";
}
public void validate(){
if("".equals(getUsername())){
addFieldError("username", getText("username.required"));
}
if("".equals(getPassword())){
addFieldError("password", getText("password.required"));
}
}
}
Interceptors
Interceptors promote the separation of concerns by separating the implementation of the cross-cutting
concerns from the action. Struts 2 comes with a set of prebuilt interceptors and interceptor stacks
that you can use out of the box. Listing 4-7 illustrates the declaration of an action that belongs to a
package that extends the struts-default package, which contains the default set of interceptors.
Listing 4-7. Declaring an Action
When you extend your package from the struts-default package, by default the defaultStack will
be used for all the actions in your package. The defaultStack is configured in the struts-default.xml
file, and it provides all the core Struts 2 functionality. The struts-default.xml file is located in the
struts 2-core.jar file. To map other interceptors to an action, you can use the interceptor-ref
element, as illustrated in Listing 4-8.
Listing 4-8. Mapping Interceptors to the Action