Search code examples
model-view-controllerstruts-1

how to to call db access method from controller to DAO class in struts


i want to call a method from controller i.e servlet. The method is located in seperate java(DAO) class. The issue is how to pass form variables from controller to java(DAO) class.


Solution

  • You can do this by using a bean (POJO) class. I will explain it by using a simple example.
    
    If your form has a field "UserName" , In your bean (POJO) class create a variable called UserName create getter/setter mathods  
    
    Ex: **JSP**  
    
        ( User Name: <input type="text" name="UserName" value="UserName"/> )
    
    **Bean (POJO) class :**
    
            public class InputBean {
                private String UserName;
    
                public void setUserName(String UserName) {
                    this.UserName = UserName;
                }
    
                public String getUserName() {
                    return UserName;
                }
            }
    
    Then you can pass the form varibles from controller to DAO **by using InputBean** class (By creating InputBean Objects in both DAO and Controller) **as the intermediate class**
    
    assume that you have a method called "add" in DAO
    
     public String add(inputBean inputBean) {
            // your code here
            try {
               // your code here
               //assume that database mapping class to relavent database table is User
    
                    User task = new User();
                    task.setUserName(inputBean.getUserName); //here the form data is passed
               }   
    
                 //your code here   
        }
    
    Then in action class you can call that method
    
    ----Action Class----
    
    InputBean inputBean = new TaskInputBean();
    
     public String insert() {
          //your code here
            try {
    
    
    
              dao.add(inputBean);
    
           //your code here        
    
            }
            return result;
        }