Search code examples
javajspmodel-view-controllerstruts2front-controller

How to work with view in Struts 2?


In plain old servlets I can use doGet and doPost methods. Where in doGet i'm forwarding user to some page and in doPost i'm proccessing data entered from the page that I gave. That all happening in one servlet.

But the Struts2 works on Front Controller pattern and instead doGet/doPost I have only execute method. So how can I properly give user some page, so then he can see it, enter data, submit and application as result proccess it in execute ?

From what I know I have two options (example on registration form):

  1. Map page to another url:

    <action name="register_display">
        <result name="success" type="dispatcher">register.jsp</result>
    </action>
    
    <action name="register"
        class="magazine.action.client.RegisterClientAction"
        method="execute">
        <result name="success" type="redirectAction">/index</result>
        <result name="error" type="redirectAction">register_display
        </result>
    </action>
    
  2. Create whole package named display and place there all view from which POST can be performed:

    <package name="display" namespace="/display" extends="struts-default">
      <action name="register">
         <result name="success" type="dispatcher">register.jsp</result>
      </action>
    ...
    </package>
    

Is there any other options ? Which one is prefered ?


Solution

  • In the standard Struts2 style, an Action class has only one work method, this is the execute method. However, you do not necessary have to follow this. You can define multiple actions in a single Action class.

    For example you make a GET request to users, which is handled in the default execute method of UsersAction.

    @Override
    public String execute() {
        // fetch the list of users
        return SUCCESS;
    }
    

    Let's suppose you would like to add a new user in this same action, by POSTing to user_add. So you define an add method:

    public String add() {
        // add the user
        return SUCCESS;
    }
    

    The struts.xml would look similar to this:

    <package name="users" extends="defaultPackage">
        <action name="users" class="com.example.UsersAction">
            <result>users.jsp</result>
        </action>
    
        <action name="user_add" class="com.example.UsersAction" method="add">
            <result type="redirect">users</result>
        </action>
    </package>
    

    In your scenario, you would render your page, which the user should see after the run of the (maybe empty) execute method. Then, you would make the post request, which would be mapped to the other method of the Action class.