1 | package spiffy.struts1; |
2 | |
3 | import org.apache.struts.action.ActionForward; |
4 | import org.apache.struts.action.ActionMapping; |
5 | |
6 | /** |
7 | * Helper class for Struts1 actions |
8 | * |
9 | * @author Kasper B. Graversen, (c) 2007-2008 |
10 | * @since 0.03 |
11 | */ |
12 | |
13 | public class StrutsActionHelper { |
14 | |
15 | /** |
16 | * Helps you forwarding from one one action to another action and carrying over the parameters. If not carried over, |
17 | * they disappear from the request scope during forward. |
18 | * <p> |
19 | * A common use case is to have the <tt>SaveAction</tt> invoke the <tt>DislayListAction</tt>. To do this in a |
20 | * fashion that changes the URL in the users browser, you set the <tt>redirect="true"</tt> in the action in |
21 | * <tt>struts-config.xml</tt> and by uisng this helper method. It will take whatever you info you provide and |
22 | * encode the url to redict to. |
23 | * |
24 | * @param actionMapping |
25 | * Your Struts object |
26 | * @param forwardName |
27 | * Name of the action in the struts-config.xml |
28 | * @param urlParams |
29 | * An array of strings where you already have set all the values as strings, e.g. strings such as |
30 | * <tt>"id=1"</tt>, <tt>name="Mr. Anderson"</tt> |
31 | * @return A struts forwarderder object |
32 | * @throws IllegalStateException |
33 | * if redirect="true" is not set in the struts config or if forward path is invalid. |
34 | */ |
35 | public ActionForward goForward(final ActionMapping actionMapping, final String forwardName, final String[] urlParams) { |
36 | // is forwarder defined in the config file? |
37 | final ActionForward forward = actionMapping.findForward(forwardName); |
38 | if( forward == null ) { return null; } |
39 | |
40 | // if redirect="false" is set in the config |
41 | if( forward.getRedirect() == false ) { throw new IllegalStateException( |
42 | "You must set your redirect='true' in your struts-config.xml for this action!"); } |
43 | |
44 | // Construct a URL |
45 | final StringBuilder url = new StringBuilder(); |
46 | if( forward.getPath() == null ) { throw new IllegalStateException( |
47 | "Can't find path to forward to in you struts-config.xml"); } |
48 | |
49 | url.append(forward.getPath()); |
50 | for(int i = 0; i < urlParams.length; i++) { |
51 | url.append(i == 0 ? "?" : "&"); |
52 | url.append(urlParams[i]); |
53 | } |
54 | |
55 | // Create a ActionForward object as Stuts does not allow to modify the existing one |
56 | return new ActionForward(forward.getName(), url.toString(), true /* = REDIRECT */); |
57 | } |
58 | |
59 | // TODO we should also have a method that takes the request scope and converts it into an Object array, so it is |
60 | // easy to transfer the request scope |
61 | }; |