Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
 
User Registration Action Class and DAO code 
 

In this section we will explain how to write code for action class and code for performing database operations (saving data into database).

 

User Registration Action Class and DAO code

                         

In this section we will explain how to write code for action class and code for performing database operations (saving data into database).

Developing Action Class

The Action Class UserRegisterAction.java process the user registration request. It saves the user information into database with the help of "SpringHibernateDao" bean.

Here is the full code of  UserRegisterAction.java:

 

 

 

package roseindia.web.struts.action;

import roseindia.services.ServiceFinder;
import roseindia.web.struts.form.UserRegisterForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class UserRegisterAction extends Action {

  public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    UserRegisterForm objForm = (UserRegisterFormform;

    //Utilities util=new Utilities();
    //      Retrieve the DAO Reference
    roseindia.dao.SpringHibernateDAO springHibernateDAO = (roseindia.dao.SpringHibernateDAO
   ServiceFinder

        .getContext(request).getBean("SpringHibernateDao");
    //By Default show the Add/Edit Page
    String forwardToPage = "input";
    String strError = "";

    try {

      

      String strParent = "0";

      boolean ValidUsernameStatus = springHibernateDAO
          .checkValidUserName(objForm.getUserid());
      

      

      //In case of form submit Add/Update the data
      if (objForm.getActionUpdateData().equals("update")) {
        //In case of Add, Add the data into database
        
        if (objForm.getAction().equals("add")) {

          if (ValidUsernameStatus == false) {

            
            roseindia.dao.hibernate.Login pojoObj = new roseindia.dao.hibernate.Login();

            pojoObj.setLoginid(objForm.getUserid());
            pojoObj.setPassword(objForm.getPassword());
            pojoObj.setAddress(objForm.getAddress());
            pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
            pojoObj.setId(objForm.getId());
            pojoObj.setEmail(objForm.getEmail());
            //Add the data
            springHibernateDAO.addUser(pojoObj);
            
            forwardToPage = "success";

          else {

            //   Create object of ActionMesssages
            ActionMessages errors = new ActionMessages();

            errors.add("invalidUsername"new ActionMessage(
                "error.invalidUsername.invalid"));
            saveErrors(request, errors);
            
            return mapping.findForward("input");
          }

        }//User updates the data, update the user details
        if (objForm.getAction().equals("update")) {
          //System.out.println("Update the Data");
          roseindia.dao.hibernate.Login pojoObj = springHibernateDAO
              .loadUser(objForm.getId().toString());
          pojoObj.setLoginid(objForm.getUserid());
          pojoObj.setPassword(objForm.getPassword());
          pojoObj.setAddress(objForm.getAddress());
          pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
          pojoObj.setId(objForm.getId());
          pojoObj.setEmail(objForm.getEmail());
          //Update the data
          springHibernateDAO.updateUser(pojoObj);
          forwardToPage = "updated";
        }
      }
      //In case of Edit retrieve the data from datbase and set the values in the form obj
      if (objForm.getAction().equals("Edit")) {

        
        HttpSession session = request.getSession();
        String id = (String)session.getAttribute("ID");

        
        //Retrieve the data from database
        roseindia.dao.hibernate.Login pojoObj = springHibernateDAO.loadUser(id);
        
        objForm.setId(pojoObj.getId());
        objForm.setUserid(pojoObj.getLoginid());
        objForm.setPassword(pojoObj.getPassword());
        objForm.setAddress(pojoObj.getAddress());
        objForm.setEmail(pojoObj.getEmail());

        objForm.setPhno(String.valueOf(pojoObj.getPhno()));
        //for the edit form
        forwardToPage = "input";
        //Set the action to update
        objForm.setAction("update");
      }

    catch (Exception e) {
      forwardToPage = "input";
      strError = e.getMessage();

      System.out.println("===> Error:" + strError);
    }
    //Display the registration form to the user
    return mapping.findForward(forwardToPage);

  }
}

Save the above code into the file UserRegisterAction.java in the project\WEB-INF\src\java\roseindia\web\struts\action directory.

Understanding the Action Class

a) Getting the SpringHibernateDao Reference
Following code gets the reference of SpringHibernate.
    //Retrieve the DAO Reference
    roseindia.dao.SpringHibernateDAO springHibernateDAO = (roseindia.dao.SpringHibernateDAO) ServiceFinder
        .getContext(request).getBean("SpringHibernateDao");
  

b) Checking for the New user Registration
Following code checks for the user restoration information. This is necessay as we using the same action class (UserRegistrationAction.java) for modification of user profile.

if (objForm.getAction().equals("add")) {

    //The Save the user information into database

}

c) Creation and populating the POJO object
We are using Hibernate so, to persist the User information into database we will first create object of Login class and populate it with requied data.

            roseindia.dao.hibernate.Login pojoObj = new roseindia.dao.hibernate.Login();

            pojoObj.setLoginid(objForm.getUserid());
            pojoObj.setPassword(objForm.getPassword());
            pojoObj.setAddress(objForm.getAddress());
            pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
            pojoObj.setId(objForm.getId());
            pojoObj.setEmail(objForm.getEmail());

c) Persisting the POJO object
Following code persists the data into database.
          
//Update the data
          springHibernateDAO.updateUser(pojoObj);

Configurations to be made into struts-config.xml

a) Add the form bean entry:
<form-bean name="UserRegisterForm" 
    type="roseindia.web.struts.form.UserRegisterForm">
</form-bean>

b) Action mapping entry:
<action
    path="/userregister"
    name="UserRegisterForm"
    scope="request"
    validate="true"
    input="/pages/user/userRegister.jsp"
    type="roseindia.web.struts.action.UserRegisterAction">
    <forward name="success" path="/pages/user/registersuccess.jsp"/>
    <forward name="input" path="/pages/user/userRegister.jsp"/>
    <forward name="updated" path="/pages/user/updatesuccess.jsp"/>
</action>

 Now the registration form is ready to test. You can compile and run the application to test the Registration Form.

                         

» View all related tutorials
Related Tags: java c hibernate web error learning com configuration spring ide class j2ee frameworks jdbc data development ui ssis process framework

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

3 comments so far (
post your own) View All Comments Latest 10 Comments:

I am getting a warning,

Connection conn = this.getSession().connection()

it is saying this method has been deprecated. Please how do I make connection to the database.

I cannot open connection. Also, please can you provide an explanation on the DAO class. i am referring to SpringHibernateDAOImpl class

Thanks
Stephen

Posted by Stephen on Wednesday, 02.13.08 @ 00:30am | #48063

can any one plz help me i m getting this error org.hibernate.exception.GenericJDBCException: Cannot open connection at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:91) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:79) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:327) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:118) at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:127) at org.hibernate.jdbc.BorrowedConnectionProxy.invoke(BorrowedConnectionProxy.java:50) at $Proxy2.createStatement(Unknown Source) at roseindia.dao.SpringHibernateDAOImpl.checkValidUserName(SpringHibernateDAOImpl.java:89) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:335) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:165) at $Proxy8.checkValidUserName(Unknown Source) at roseindia.web.struts.action.UserRegisterAction.execute(UserRegisterAction.java:38) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Login failed for user 'sa'. at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source) at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source) at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processErrorToken(Unknown Source) at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReplyToken(Unknown Source) at com.microsoft.jdbc.sqlserver.tds.TDSLoginRequest.processReplyToken(Unknown Source) at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReply(Unknown Source) at com.microsoft.jdbc.sqlserver.SQLServerImplConnection.open(Unknown Source) at com.microsoft.jdbc.base.BaseConnection.getNewImplConnection(Unknown Source) at com.microsoft.jdbc.base.BaseConnection.open(Unknown Source) at com.microsoft.jdbc.base.BaseDriver.connect(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:241) at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:80) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:324) ... 33 more ===> Error:Cannot open connection

Posted by Narendra Singh on Friday, 06.29.07 @ 20:50pm | #20393

Presentaion methology & resource avaiability is rocking in the tutorial.
..............................................
But i am having my query pls solve...Letyou in step whats i have done .
1. Copy project.zip and extract it into webapps directory in tomcat.
2. Installed MYSQL and create database & table as prescribed.
3. As spring,hibernate & struts .jar are already been added so I think no need to install them seprately,as i have not done.Just copy project directory into Tomcats webapps folder.
..............
Error Facing while Executing
HTTP Status 500 -

--------------------------------------------------------------------------------

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext-hibernate.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyAccessExceptionsException: PropertyAccessExceptionsException (1 errors); nested propertyAccessExceptions are: [org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [com.mysql.jdbc.Driver]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.Driver]
org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:523)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

***********************************
Whats The Solution:Pls Let Me Know Where I Am Wrong.

Thanks

Posted by Loyal on Wednesday, 03.7.07 @ 16:27pm | #10986

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
Search Tutorials:

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.