I am migrating an application from Struts 1 to Struts 2. I have encountered the following code snippet. Please let me know how to replace the code snippet in Struts 2.
protected ActionForward getActionForward(FilterContext ctx, String key, boolean redirect) {
HashMap filterForwards = ctx.getFilterForwards();
String forwardPage = (String)filterForwards.get(key);
if(forwardPage == null)
return null;
return new ActionForward(forwardPage, redirect);
}
And another code snippet is like this:-
protected void setError(HttpServletRequest req, String msg) {
ActionMessages errors = new ActionMessages();
errors.add("exception", new ActionMessage(MSG_KEY, msg));
req.setAttribute(Globals.ERROR_KEY, errors);
}
Should I replace the above code with addActionError(msg)
?
In Struts 1 you should return ActionForward
from the execute
method. Struts 2 returns a result code of type String
. So the code where ActionForward
is expected should be replaced with result code. The action result should be configured to the action the same way like you configure forwards in Struts 1.
Create two result configs: one is redirectAction
result type, and another dispatcher
result type. Like this
<result name="redirect" type="redirectAction">${forwardPage}</result>
<result>${forwardPage}</result>
The code should be replace with
private String forwardPage;
public String getForwardPage() { return forwardPage; }
public void setForwardPage(String forwardPage) {
this.forwardPage = forwardPage;
}
protected String getActionForward(FilterContext ctx, String key, boolean redirect) {
HashMap filterForwards = ctx.getFilterForwards();
String forwardPage = (String)filterForwards.get(key);
if(forwardPage == null)
return NONE;
if (redirect) {
setForwardPage(forwardPage);
return "redirect";
} else {
setForwardPage(forwardPage)
return SUCCESS;
}
}
The errors are provided by the ActionSupport
class that your action should inherit. Then you can use the code
protected void setError(String msg) {
addActionError(getText("exception", new Object[]{msg}));
}
In the JSP you can display errors with
<s:actionerror/>