Hello,

I am building a struts2-hibernate-mysql application. A user after
navigating through some pages reaches a pages where all the records on
the database are listed and can perform crud operations.

The jsp which iterates and displays the records is:

<%@ taglib prefix="s" uri="/struts-tags"%>

<p>Persons found on database</p>
<a href="<s:url action='adduser'/>">Add new User</a>
<s:if test="persons.size > 0">  
        <table>
                <s:iterator value="persons">
                        <tr id="row_<s:property value="id"/>">
                                
                                <td>
                                        <s:property value="id" />
                                </td>
                                <td>
                                        <s:property value="firstName" />
                                </td>
                                <td>
                                        <s:property value="lastName" />
                                </td>
                                <td>
                                                <s:url action="remove" 
var="remURL">
                                                        <s:param name="id" 
value="id" />
                                                </s:url>
                                <a href="<s:property value 
="remURL"/>">Remove</a>      
                                </td>
                                <td>
                                                <s:url action="edit" 
var="editURL">
                                                        <s:param name="id" 
value="id" />
                                                </s:url>
                                        <a href="<s:property value 
="editURL"/>">Edit</a>
                                </td>
                                <td>
                                        <a style="color: #FF0000" 
href="Accounts">View account details</a>
                                </td>
                        </tr>
                </s:iterator>
        </table>
</s:if>
<a href="<s:url action='admin'/>">Back to Administrator's homepage</a>

---As you can see within the above jsp an "edit" link is generated for
every record and the record id is passed as a parameter to the URL,
with: <s:param name="id" value="id" />

When the user follows the "edit" link, the URL forms like this:

http://localhost/MyApp/edit.action?id=38

The record identifier is passed as a parameter in the URL: ?id=38

The link brings the user to a new form to perform a simple edit of the
record; first name and last name:

The jsp with the edit form is the following:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

        <head>
    <title>Update User</title>
    <s:head/>
        </head>

        <body>
                <h4>Edit information for selected user</h4>
                <s:form action="save">          
          <s:textfield name="person.firstName"
value="%{person.firstName}" label="First Name"/>
          <s:textfield name="person.lastName" label="Last Name"/>
          <s:hidden name="person.id" value="#attr.id" label="Primary Key" />
          <s:submit/>
                </s:form>       
                
        </body>
        
</html>

The aim is to have the hidden field pre-filled with the value taken
from the URL parameter as soon as the user clicks on the "edit" link
and reaches the new form to update a record. Unfortunately so far I
have not been able to retrieve that parameter and use its value to
fill that texfield. The id value is always null.

The consequence is that the code performs a new insert instead of an
update, it sees the null id and assumes a new record must be inserted.
Could anyone perhaps provide some advice how can I solve this?

If required my struts.xml file is:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd";>

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
    <constant name="struts.devMode" value="false"/>

    <package name="default" namespace="/" extends="struts-default">
        <action name="Menu">
            <result>pages/firstpage.jsp</result>
        </action>

         <action name="user">
            <result>pages/user/user_auth.jsp</result>
        </action>

        <action name="admin">
            <result>pages/admin/admin_auth.jsp</result>
        </action>

        <action name="list" method="execute" class="org.user.PersonAction">
                <result>/pages/list.jsp</result>
                <result name="input">pages/list.jsp</result>
        </action>

        <action name="remove" method="remove" class="org.user.PersonAction" >
            <result>/pages/list.jsp</result>
            <result name="input">pages/list.jsp</result>
        </action>

        <action name="adduser">
            <result>pages/user/Registration.jsp</result>
        </action>

        <action name="save" method="save" class="org.user.PersonAction" >
            <result>/pages/list.jsp</result>
            <result name="SUCCESS">pages/list.jsp</result>
        </action>

        <action name="edit">
            <result>pages/user/UpdateAccountForm.jsp</result>
        </action>



    </package>
    <include file="org/visitor/visitor.xml"/>

</struts>

-----And the action class is:

package org.user;

import java.util.List;
import java.util.Map;

//import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ParameterAware;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.Action;

public class PersonAction implements Preparable, ParameterAware{
        
        private PersonService service = new PersonServiceImpl();
    private List<Person> persons;
    private Person person;
    private Integer id;
    private Map parameters;



    public PersonAction(){}

    public PersonAction(PersonService service) {
        this.service = service;
    }

    public String execute() {
        System.out.println("Inside execute method");
        this.persons = service.findAll();
        return Action.SUCCESS;
    }

    public String save() {
    //  HttpServletRequest request = (HttpServletRequest)
getServletContext.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
         Map map = getParameters();
         id = (Integer)map.get("id");
         System.out.println("In PersonAction rertieving request param "+id );
        //      parameters = this.getParameters();
    //  id = (Integer) parameters.get(id);
   //   person.setId(id);
        System.out.println("In PersonAction before service.save");
        this.service.save(person);
        System.out.println("In PersonAction after service.save");
        System.out.println("In PersionAction" + " " +
person.getFirstName()+" "+person.getLastName()+" "+person.getId());
        return execute();
    }

    public String remove() {
        service.remove(id);
        return execute();
    }

    public List<Person> getPersons() {
        return persons;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void prepare() throws Exception {
        if (id != null)
            person = service.find(id);
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
    public void setParameters(Map parameters) {
              this.parameters=parameters;
             }
    public Map getParameters() {
              return parameters;
             }


}


---- I have also tried unsuccessfully to retrieve the parameter value
from the action code, but always get null. Also the delegate class
implementing the actual action methods is the following:

package org.user;

import java.util.List;

import org.hibernate.*;
import org.persist.util.*;

//import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;
//import org.springframework.web.context.ContextLoaderListener;
//import org.hibernate.transaction.JDBCTransactionFactory;

public class PersonServiceImpl implements PersonService {
        
        Session session;

    public PersonServiceImpl() {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

        
        public void setSession(Session s){
                this.session = s;
        }
        public Session getSession(){
                if (session == null){
                        session = HibernateUtil.getSession();
                }
        return session;
        }

        @Override
        public void clear() {
                getSession().clear();
                
        }

        @Override
        public Person find(int id) {
                try {
                        getSession().beginTransaction();
                        Query q = session.createQuery("from Person p where 
p.id=:id");
                        q.setInteger("id",id);
                        return  (Person)q.uniqueResult();
                        }
                finally {
                        //getSession().close();
                }
        }

        @SuppressWarnings("unchecked")
        @Override
        public List<Person> findAll() {
                try {
                        Session session = HibernateUtil.getSession();
                        session.beginTransaction();
                        Query q = session.createQuery("select p FROM Person p");
                        return q.list();
                }
                catch(Exception e){
                        System.out.print("Error while fetching "+e);
                        return null;
                }
                finally {
                        //session.close();
                }
        }

        @Override
        public void flush() {
                getSession().flush();           
        }

        @Override
        public void remove(int id) {
                Person person = find(id);
                Session session = HibernateUtil.getSession();
                Transaction tx = null;
                if (person != null){
                        try {
                                tx = session.beginTransaction();
                                person =(Person)session.load(Person.class,id);
                                session.delete(person);
                                tx.commit();
                        }catch (RuntimeException e) {
                                if(tx != null) tx.rollback();
                                throw e;
                        } finally {
                                session.close();
                        }
                }
                
        }

        @Override
        public void save(Person person) {
                 Session session = HibernateUtil.getSession();
                 Transaction tx = session.beginTransaction();
                     try {              
                         if (person.getId() == null) {
                                 System.out.println("id = null, inside if 
block");
                             session.persist(person);
                             System.out.println(person.getFirstName()+"
"+person.getLastName()+" "+person.getId());
                         } else {
                                 System.out.println("id not null, inside else 
block");
                             session.merge(person);
                             System.out.println(person.getFirstName()+"
"+person.getLastName()+" "+person.getId());
                         }
                        tx.commit();
                    } catch (RuntimeException e) {
                         if (tx.isActive()) tx.rollback();
                         throw e;
                     }
                
                /*Session session = HibernateUtil.getSession();
                System.out.println("1");
                Transaction tx=null;
                System.out.println("2");
                if (person.getId() == null) {
                        System.out.println("3");
                        System.out.println(person.getFirstName()+" 
"+person.getLastName()+"
"+person.getId());
                        try {
                                tx = session.beginTransaction();
                                session.persist(person);
                                System.out.println("4");
                                tx.commit();
                                System.out.println("5");
                        } catch (RuntimeException e) {
                                if(tx != null) tx.rollback();
                                System.out.println("6");
                                throw e;
                        }
                        
        } else {
                System.out.println("7");
                try {
                                tx = session.beginTransaction();
                                System.out.println("8");
                                session.merge(person);
                                System.out.println("9");
                                System.out.println(person.getFirstName()+"
"+person.getLastName()+" "+person.getId());
                                tx.commit();
                        } catch (RuntimeException e) {
                                if(tx != null) tx.rollback();
                                System.out.println("10");
                                throw e;
                        }               

        }*/

                
                
                /*try {
                        tx = session.beginTransaction();
                        session.saveOrUpdate(person);
                        tx.commit();
                } catch (RuntimeException e) {
                        if(tx != null) tx.rollback();
                        throw e;
                } finally {
                        session.close();
                }*/
                
        }

}


---- Thank you in advance for any help on this situation.
Regards to everyone!

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscr...@struts.apache.org
For additional commands, e-mail: user-h...@struts.apache.org

Reply via email to