Monday, May 2, 2011

Creating a Struts 2 "Welcome" page

Creating a "welcome" page in a Java web application is usually a simple matter.  Just modify the web.xml with your <welcome-file> and away you go.  However, it's not so simple to have my <welcome-file> point to a Struts 2 Action.  It seems the web container is expecting a JSP or HTML file in the <welcome-file> tag.

I did some Googling and read some posts on stackoverflow and theserverside on this same issue.  There were several suggested approaches.  The two most common suggestions were:
  1. Create a index.jsp and issue a <% response.sendRedirect(myaction.do); %> or alternatively a <jsp:forward page="/myaction.do" />.  Of course you'll also need to add index.jsp as a <welcome-file> in your web.xml.
  2. Create an empty file named welcome.do.  Add welcome.do to your <welcome-file> tag and create a Struts Action mapping for welcome.do.  This is a nice little hack and Struts will go ahead and serve your Action.
I decided to use the second suggestion in my Struts 2 web application.  Here's the steps I used.
  1. Create an empty file named "welcome.action" in "FlashCardsWeb\WebContent"
  2. Modified the web.xml as follows:
    <welcome-file-list>
        <welcome-file>welcome.action</welcome-file>
    </welcome-file-list>
  3. Modified the struts.xml to create the following Action.  "baseLayout" is Tiles definition that includes my header, menu, body, and footer.
    <action name="welcome">
        <result name="success" type="tiles">baseLayout</result>
    </action>
I'm sure there are other approaches.  What are you using?  Feel free to comment with your comments or solution.  Thanks!

2 comments:

  1. Interesting hack (the second option). Worked like a charm!

    ReplyDelete
  2. Second Options works perfectly!

    ReplyDelete