How to use ModelDriven in Struts 2

Talking about Struts 2 again
. I wanna talk (or write) about this because is very interesting, for me it remembers me the way of work on Struts 1. For those that doesn't know what am i talking about, i'm going to explain you. In Struts 1, the way of work with Action and form properties is a little bit different of default Struts 2 way. In struts 1 we have the actions that doesn't contain any form property or getter/setter method, like this:
import....
public class LoginAction extends LookupDispatchAction {
public ActionForward logMeIn(HttpServletRequest request,
HttpServletResponse response,
ActionMapping mapping,
ActionForm form) {
LoginForm loginForm = (LoginForm) form;
if (loginForm.getUsername().equals("admin") &&
loginForm.getPassword().equals("admin")) {
return mapping.findForward("enter");
} else {
return mapping.findForward("fail");
}
}
}
And, in other class, the Action Form where we can find the properties with respective getter/setter methods and optionally, struts 1 server side validation:
But, in Struts 2 it changes a little bit because properties, getter/setter methods and validation are in the action. For the previous example, it's version on Struts 2 will look like this:
public class LoginAction {
private String username;
private String password;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public String logMeIn() {
if (getUsername().equals("admin") &&
getPassword().equals("admin")) {
return "enter";
} else {
return "fail";
}
}
Free from extends and strange return types in methods but more charged with properties and getter/setter methods, for some people it's better, for another people it sucks. In my case i like the fact that i don´t need to extend my actions from some classes (altought you have to do that if you want to inject additional funcionality to your action like validation, prepare scripts and so on) and a simpler way to declare action methods, but i dislike the fact that all is inside the action.
But don't worry people, Struts 1 developer that migrated to Struts 2 can still use the same model Action - Action Form like Struts 1 in struts 2
, how to do that?
How to validate through annotations: Struts 2

Hi to all. I've studied some stuff about struts 2 those days so i've learn a lot of new things like this post topic. Normally, what do you do when you want to implement a basic validation on Struts 2? The steps about how to do that are:
- Assure that you're using defaultStack interceptor stack because inside it are workflow and validation interceptors that are responsible of execute validation logic and redirect to appropiate result when validation triggers.
- Define a result named "input" in action's declaration on struts.xml . This is the result where validation must redirect automatically if exists validation errors. If input result is not defined it will give an error of result not found.
- Override validate() method on your action.
- Write your own validation logic inside it, that must add error messages when it fails to properly validation mechanism. For example, if i validate that a field must be a number and greater than 1000, if it doesn't pass the validation it must add a error message using addActionError() or addFieldError() (To follow standards you should use addFieldError() ), like this:
if (fieldOne == null || fieldOne.equals("")) { addFieldError("fieldOne", "Field one must not be empty."); } if (fieldTwo == null || Integer.valueOf(fieldTwo) < 30) { addFieldError("fieldTwo", "Field two must be greater or equal than 30."); } - (Optional) in your jsp you can define <s:fielderror> or <s:actionerror> tags to print your validation messages. As you can guess, <s:fielderror> prints validation errors added with addFieldError() and <s:actionerror> to print action error messages added with addActionError(). To print validation errors from fieldOne and fieldTwo you have to define <s:fielderror> like this:
<s:fielderror cssClass="cssClassForUllistwithLi" > <s:param>fieldOne</s:param> <s:param>fieldTwo</s:param> </s:fielderror>
- Run your app
This is the basic way. But if you want to validate through annotations is easier and faster, you have to do this:
How to avoid validation on Action call – Struts 2
As you know, like Struts 1, Struts 2 allow us to define server side validations when you call an action. This is very useful because sometimes javascript client side validation is not enought when we want to validate input entries against data from DB or do complex validations.
How to define validations in JAVA Struts 2? First your action must extend ActionSupport class, and override it's method validate that has te following signature:
public void validate() {}
Inside validate() you define your validations and, if you add messages to ActionErrors or FieldErrors, Struts 2 automatically detects that it must redirect to input result defined in action's declaration in struts.xml, like this:
<action name="login"> <interceptor-ref name="defaultStack" /> <result name="homePage">/login/login.jsp</result> <result name="input">/login/login.jsp</result> ... <result name="backToLoginPer">/login/login.jsp</result> </action>
The problem is that sometimes you want that validation applies only on certain action calls, that is, avoid validation on certain action calls. How to do this?
Dynamic mime type on stream result – Struts 2
Hi to all. A reader (Staci) asks about how to dinamically define the mime type of stream result type on Struts 2, for example define that the stream result will serve a pdf file or excel file. Well, as i see, that can bea achieved in 2 ways:
- Defining a stream result for each mime type that you want to return in the struts.xml
- Using wildcards to define the mime type and file extension in struts.xml
- Using parameters on struts.xml
Both options are viable, but the first extendes more and more the more kind of mime types that you want to support, because you have to define a result for each mime type and then send a parameter or something like that to define the result that you want to get.
But i'm going to write about the second and third options. First: Using wildcards. FIrst, imagine that you have a simple html to call the action method that gives us a file:
<html> <head> <title>Name Collector</title> </head> <body> <a href="/demoStruts2/pdf_pdf_WildCardRaw!giveMeMyFile.action">Get PDF file</a><br /> <a href="/demoStruts2/vnd.ms-excel_xls_WildCardRaw!giveMeMyFile.action">Get XLS file</a> </body> </html>
Automatic raw data output – Struts 2
As you know (mainly web developers), when you want to return some kind of data as a response (like a PDF document, an excel file download, and so on) you have to do something like this:
ServletOutputStream out = servletResponseObj.getOutputStream();
servletResponseObj.setContentType("application/pdf");
out.write(myByteArray);
out.flush();
out.close();
return null;
In synthesis, you have to get some stream like an byte array, instantiate an OutputStream object to write the stream in the response buffer and so on. We ask ourselves "How to do this automatically?", well, in Struts2 now is possible to automatically return raw data without interact with OutputStream , HttpServletResponse objects, as you can see next...







