1

I am getting an error while accessing the web page. here is my code -

web.xml file -

 <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

dispatcher servlet with name - "dispatcher-servlet.xml"

    <context:annotation-config />
    <context:component-scan base-package="com.webProject.controller"></context:component-scan>
    <!-- <context:component-scan base-package="com.webProject">
        <context:include-filter type="aspectj" expression="com.webProject.*" />
    </context:component-scan>
    -->

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/school" />
        <property name="username" value="root" />
        <property name="password" value="test" />
    </bean>
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="mysqlDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.webProject.model.Student</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="connection.autocommit">true</prop>
            </props>
        </property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="mySessionFactory" />
    </bean>
    <!-- <bean id="studentDao" class="com.webProject.dao.StudentDaoImpl"></bean>-->


</beans>

Student controller class -

package com.webProject.controller;

@Controller
@RequestMapping("/Student")

public class StudentController {
@Autowired
private IStudentDao studentDao;
//List<Student> students;

/*public StudentController() {
    students = new ArrayList<Student>();
}*/

public IStudentDao getStudentDao() {
    return studentDao;
}

public void setStudentDao(IStudentDao studentDao) {
    this.studentDao = studentDao;
}

@RequestMapping(value="details/{number}",method=RequestMethod.GET)
public String studentDetails(@PathVariable("number") int studentNumber, Model model){
    //Student student = this.students.get(studentNumber);
    Student student = (Student) getStudentDao().load(new Long(studentNumber));
    model.addAttribute("student",student);
    model.addAttribute("studentNumber", Integer.toString(studentNumber));
    return "studentDetails";

}

@RequestMapping(value="addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("student") Student student, Model model){

    if(student != null){
        getStudentDao().save(student);
        //this.students.add(student);
        model.addAttribute("student", student);
        model.addAttribute("studentNumber", Integer.toString(getStudentDao().count()));
        return "studentAddSuccess";
    }else{
        throw new NullPointerException();
    }   
}

@RequestMapping(value="studentRegistration")
public String sendStudentForm(Model model){

    Student student = new Student();
    model.addAttribute("student", student);

    return "studentForm";
}

@RequestMapping(value="delete/{studentNumber}")
public String deleteStudent(@PathVariable("studentNumber") int studentNumber, Model model){

    Student student = (Student) getStudentDao().load(new Long(studentNumber));
    model.addAttribute("std", student);
    getStudentDao().deleteById(new Long(studentNumber));
    return "deleteStudent";

}


}

studentform.jsp

  <body>
    <form:form method="post" modelAttribute="student" action="addStudent">

<table>

    <tr>
        <td>Student Name</td>
        <td>form:input path="studentName"</td>          
    </tr>
    <tr>
        <td>Department</td>
        <td>form:input path="department"</td>
    </tr>
    <tr>
        <td>College</td>
        <td>form:input path="collegeName"</td>
    </tr>
    <tr>
        <td colspan="3"><input type="submit" /></td>
    </tr>

</table>

   </form:form>

</body>

when i mention - this i get an error as "Resource not found". so i tried including all my packages as-

 <context:component-scan base-package="com.webProject.controller"></context:component-scan>
<context:component-scan base-package="com.webProject.dao"></context:component-scan>
<context:component-scan base-package="com.webProject.model"></context:component-scan> but then also i get same "resource not found" error. i tried another way as mentioned in another thread - http://stackoverflow.com/questions/7914363/injection-of-autowired-dependencies-failed
<context:component-scan base-package="com.webProject">
     <context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>

but then also same result - "Resource not found".

so only when i give this base-package="com.webProject.controller", then i dont get "Resource not found error", but then it get another error -

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentController': Injection of autowired dependencies failed;

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.webProject.dao.IStudentDao

com.webProject.controller.StudentController.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching

bean of type [com.webProject.dao.IStudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

then i tried to inject the studentDao as , then i also i get an error.

I am using Tomcat to deploy this artifact. and using maven to build this project. i am not sure how it spring+ hibernate+ maven project works in tomcat?

I have recently started programming using spring and hibernate and this is my first project using these technologies. so please pardon me if i am making some basic mistake.

can you please help me with some solution.

student Dao -

package com.webProject.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.webProject.model.*;

public abstract class AbstractHibernateDAOImpl implements AbstractDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    protected Class domainClass = getDomainClass();

    /**
     * Method to return the class of the domain object
     */
    protected abstract Class getDomainClass();

    @SuppressWarnings("unchecked")
    public PersistentObject load(Long id) {
        return (PersistentObject) getHibernateTemplate().load(domainClass, id);
    }

    public void update(PersistentObject t) {
        getHibernateTemplate().update(t);
    }

    public void save(PersistentObject t) {
        getHibernateTemplate().save(t);
    }

    public void delete(PersistentObject t) {
        getHibernateTemplate().delete(t);
    }

    @SuppressWarnings("unchecked")
    public List<PersistentObject> getList() {
        return (getHibernateTemplate().find("from " + domainClass.getName()
                + " x"));
    }

    public void deleteById(Long id) {
        Object obj = load(id);
        getHibernateTemplate().delete(obj);
    }

    @SuppressWarnings("unchecked")
    public void deleteAll() {
        getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException {
                String hqlDelete = "delete " + domainClass.getName();
                int deletedEntities = session.createQuery(hqlDelete)
                        .executeUpdate();
                return null;
            }

        });
    }

    public int count() {
        List list = getHibernateTemplate().find(
                "select count(*) from " + domainClass.getName() + " x");
        Integer count = (Integer) list.get(0);
        return count.intValue();
    }

}

student dao interface -

package com.webProject.dao;

public interface IStudentDao extends AbstractDao{

}

student dao implementation -

package com.webProject.dao;

import org.springframework.stereotype.Repository;

import com.webProject.model.Student;


@Repository ("studentDao")
public class StudentDaoImpl extends AbstractHibernateDAOImpl implements IStudentDao{


    @Override
    protected Class getDomainClass() {
        return Student.class;
    }

}
Rahul Baiswar
  • 11
  • 1
  • 3
  • Have you enabled DEBUG logging of the org.springframework package? It will show you all the beans and their names loaded into the ApplicationContext. Example `log4j.logger.org.springframework=DEBUG` – Brad Aug 15 '12 at 09:24

1 Answers1

1

If your DAO classes is placed in different packages with controller classes then you should change your component scan element:

<context:component-scan base-package="com.webProject">

Also check that you have annotated your DAO classes with @Repository (or @Component) annotation.

dimas
  • 6,033
  • 36
  • 29
  • when i give , then it gives an error "resource not found" – Rahul Baiswar Aug 15 '12 at 08:21
  • and yes i have marked my Dao class as @Repository ("studentDao") – Rahul Baiswar Aug 15 '12 at 08:22
  • As I understand IStudentDao is interface? Or class? – dimas Aug 15 '12 at 08:25
  • Try to use AbstractDao as a type of property instead of IStudentDao. – dimas Aug 15 '12 at 08:29
  • stuck in basic problem - when i mention base-package= "com.webProject.*", then it says "resource not found", but when i give base-package="com.webProject.Controller" then it gives error that StudentDao cannot be autowired. i think second error is logical because that class cannot be scanned for annotation, so cannot be autowired! Not sure why "com.webProject.*" doesnt work?? – Rahul Baiswar Aug 16 '12 at 01:17
  • Because you don't need to use wildcards when you specify base-package. You should specify one package that will be used as base during scanning. When you specify base package then Spring will automatically scan all subpackages. So in your example you should use base-package="com.webProject", not base-package="com.webProject.*". – dimas Aug 16 '12 at 06:08