VisualBuilder
  Home > Jsp > Tutorials > Writing the Struts Business Component - Struts Tutorial
Tell a friend
Link to us
Total Members
      Members: 84661
     
Sitemap Forum Chat
Home
Struts Tutorial Home
1 . What is Struts?
2 . Why do we need Struts?
3 . Advantages of Struts
4 . Setting up Eclipse for Web Development
5 . Registration Case Study
6 . Setting up Struts project in Eclipse
7 . Creating an ODBC Data source
8 . Configuring Application Server
9 . Struts Configuration
10 . Writing the User class
11 . ResourceManager
12 . Writing the Struts Business Component
13 . Creating the Action Class
14 . Adding ActionForward
15 . Deploy the Struts Application
16 . Adding the Form bean
17 . Configuring Form Bean in struts-config.xml
18 . Using Struts Tag Libraries
19 . Listing all Users - Struts Iterator Looping
20 . Add User Action - New Struts Action Class
21 . Add User View
22 . Validating Struts Form Bean
23 . Review of the Struts Tutorial
24 . Introduction
25 . DispatchAction
26 . DispatchAction Example Continued...
27 . Introduction to DynaActionForm
28 . DynaActionForm Example Continued...
29 . Struts solution to Duplicate Form Submission (Token mechanism)
30 . Introduction to Validation framework
31 . Example Continued Validation Framework.
32 . Client Side Validation
33 . Introduction to Standard Validator-Rules.xml
34 . Creating custom Valdator rules
35 . Extending the Validator Rules with the inherited SubForm Classes.-2
36 . Internationalization in struts application
37 . Exception Handling in Struts
38 . Creating Custom Exception Handlers in Struts-1
39 . Creating Custom Exception Handlers in Struts.-2
40 . Creating Plugin for the Struts Application. -1
41 . Creating Plugin for the Struts Application. -2
42 . WildCard Character mapping for the Actions-1.
43 . WildCard Character mapping for the Actions-2.
44 . WildCard Character mapping for the Actions-3.
45 . Uploading the Files to Server Using Struts-1
46 . Uploading the Files to Server Using Struts-2
47 . Introduction to Modules in Struts Application
48 . Modules Example-1
49 . Modules Example-2
50 . Customizing the ActionServlet Class for the application-1.
51 . Customizing the ActionServlet Class for the application-2.
52 . Customizing the ActionServlet Class for the application-3.
53 . Customizing the ActionServlet Class for the application-3.
54 . Customizing RequestProcessor Class for the application-1.
55 . Customizing RequestProcessor Class for the application.-2
56 . ComposableRequestProcessor in Struts 1.3
57 . Adding New Command Objects in Struts CoR Pattern
58 . Security in Struts
59 . Example for the Application Managed Security-1
60 . Example for the Application Managed Security-2
 
 
JSP Home
JSP Members (18709)
JSP Member Articles ( 11 )
JSP Discussion (71)
JSP Q & A ( 87 )
- JSP Ask Question
- JSP Questions
- JSP Unanswered Questions
JSP Resources
JSP Source Code (172)
JSP Articles (34)
JSP Blogs (333)
JSP Jobs (0)
JSP Components (10)
JSP Books (9)
JSP Websites (13)
JSP News (12)
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.Net Security,Internationalisation And Deployment
ASP.NET Tutorial
C# Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (451 )
Source Code (3275 )
Articles (359 )
Books (372 )
Components (1596 )
News (892 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise

Jsp struts Tutorial
 Writing the Struts Business Component
  << Prev: ResourceManager Next: Creating the Action Class >>


Now let us write our business class that has the ability to perform several actions on the user like adding a new user to the database,updating an existing user,deleting a user or fetching a user from the database. Let us call this class a UserManager.


package com.visualbuilder.struts.db;

public class UserManager {
         
private static UserManager mgr = null;

         
private UserManager()
        
 {
         
 }
         
public static UserManager getInstance()
         
{
                   
if(mgr == null)
                   
{
                             
mgr = new UserManager();
                     }
                    
return mgr;
          
 }
}


Because for one application,there can exist only a single UserManager,we have made the UserManager a singleton. We will use UserManager.getInstance() whenever we need an instance of UserManager.


Connecting to a database
The purpose of the UserManager is to provide an interface between the database and the client applications that need access to the database.  Let’s connect to the database and add the following code in the constructor.


String driverClass = ResourceManager.getString("database.driver");


String dbUrl = ResourceManager.getString("database.url");


String dbUser = ResourceManager.getString("database.user");


String dbPassword = ResourceManager.getString("database.password");
try{
            
Class.forName(driverClass);
            
con = DriverManager.getConnection(dbUrl,dbUser,dbPassword);
}catch(Exception exp){
          
System.err.println("Could not connect to dtabase.\n" exp.getMessage());
}


 
Where con is a global variable of type java.sql.Connection. 
Now that we have connected to the database,let us add the necessary methods to manipulate the users. After adding these methods,UserManager


package com.visualbuilder.struts.db;


import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;


import com.visualbuilder.struts.ResourceManager;
import com.visualbuilder.struts.beans.User;


public class UserManager {
        private static UserManager mgr = null;
        private Connection con = null;
       
        private UserManager()
        {
                String driverClass = ResourceManager.getString("database.driver");
                String dbUrl = ResourceManager.getString("database.url");
                String dbUser = ResourceManager.getString("database.user");
                String dbPassword = ResourceManager.getString("database.password");
                try{
                        Class.forName(driverClass);
                        con = DriverManager.getConnection(dbUrl,dbUser,dbPassword);
                }catch(Exception exp){
                        System.err.println("Could not connect to dtabase.\n" exp.getMessage());
                }
        }
        public void saveUser(User user) throws SQLException
        {
                if(user == null)
                        throw new SQLException(ResourceManager.getString("save.user.null"));
                Connection connection = getConnection();
               
                PreparedStatement pstmt = connection.prepareStatement("insert into users(user_id,first_name,last_name,age,email) values(?,?,?,?,?)");
                pstmt.setString(1,user.getUserId());
                pstmt.setString(2,user.getFirstName());
                pstmt.setString(3,user.getLastName());
                pstmt.setInt(4,user.getAge());
                pstmt.setString(5,user.getEmail());
               
                pstmt.executeUpdate();
               
                pstmt.close();
        }      
        public User getUser(String userId) throws SQLException
        {
                if(userId == null || userId.length() == 0)
                        throw new SQLException(ResourceManager.getString("retrieve.user.null"));
                Connection connection = getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("select * from users where user_id=&apos;" userId "&apos;");
                User user = null;
                if(rs.next())
                {                      
                        user = new User(userId);
                        user.setFirstName(rs.getString("first_name"));
                        user.setLastName(rs.getString("last_name"));
                        user.setAge(rs.getInt("age"));
                        user.setEmail(rs.getString("email"));
                }
                rs.close();
                stmt.close();
                return user;
        }
        public List list() throws SQLException
        {
                Connection connection = getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("select * from users");
                User user = null;
                List list = new ArrayList();
                while(rs.next())
                {                      
                        user = new User(rs.getString("user_id"));
                        user.setFirstName(rs.getString("first_name"));
                        user.setLastName(rs.getString("last_name"));
                        user.setAge(rs.getInt("age"));
                        user.setEmail(rs.getString("email"));
                        list.add(user);
                }
                rs.close();
                stmt.close();
                return list;
        }
        private Connection getConnection() throws SQLException
        {
                if(con == null)
                        throw new SQLException(ResourceManager.getString("database.notConnected"));
                return con;
        }
        public static UserManager getInstance()
        {
                if(mgr == null)
                {
                        mgr = new UserManager();
                }
                return mgr;
        }
        public void finalize()
        {
                try{
                        con.close();                   
                }catch(Exception exp){}
        }
}


We have used several properties in this class. Add these properties in the ApplicationResources.properties file.


#database connection properties
database.driver = sun.jdbc.odbc.JdbcOdbcDriver
database.url = jdbc:odbc:users
database.user = ""
database.password = ""


#User operations messages

save.user.null = User is null
retrieve.user.null = User is null
user.notFound = User not found
database.notConnected = Not connected to a database


Now we have all the business functions available,we are ready to move to the formal development of the struts based application.


  << Prev: ResourceManager Next: Creating the Action Class >>
Jsp Struts Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
 
ADVERTISEMENT
Partner List
Code Project
ASP Alliance
More
 
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising