How to maintain the session using Struts2 and hibernate?

前端 未结 1 760
深忆病人
深忆病人 2021-01-15 20:25

I need to know how to maintain session for one form and multiple input[Name,City,Country] using Struts2 and finally data will stored to database using hibernate

1条回答
  •  天涯浪人
    2021-01-15 21:04

    You should map the buttons to the method in action. The default action mapper allows to use button names or method attribute to specify the method other than used by the form mapping. For example

    
        
        
        
    
    

    Now, in the action you implement SessionAware

    public class PersonAction extends ActionSupport implements SessionAware {
    
      private Person person = new Person();
    
      public Person getPerson() {
        return person;
      }
    
      public setPerson(Person person){
        this.person = person;
      }
    
      private Map session;
    
      public setSession(Map session){
        this.session = session;
      }
    
      public String execute() { //Create persons
        List personList = (List) session.get("personList");
        for (Person p : personList)
         getPersonService().save(p); // save to db
        //clear the list
        personList.clear();
        return SUCCESS;
      }
    
      public String add() { //Add person
        List personList = (List) session.get("personList");
        if (personList == null) {
          personList = new ArrayList();
          session.put("personList", personList);
        }
        personList.add(person);
        return SUCCESS;
    
      }
    
    } 
    

    Now, you have separated logic via methods mapped to a corresponding button. To make working be sure you have DMI (Dynamic Method Invocation) turned on (by default is on) and interceptors stack defaultStack is applied to the action config (by default it's used).

    struts.xml:

    
    
    
    
      
    
      
        
          /person.jsp
        
      
    
    

    SessionAware is a interface that your action or base action should implement if you want to use servlet session to put into your objects. More about it here.

    ActionContext is a container placeholder for the action invocation, more detailed explanation is here.

    0 讨论(0)
提交回复
热议问题