无法通过servlet.xml设置会话工厂

时间:2014-11-10 06:55:43

标签: java xml spring hibernate

我想在DAO类中设置会话工厂但在执行后会抛出NULLPointer异常。在我的课程中,我通过@Autowired注释设置sessionFactory变量,但它无法设置会话工厂。 我正在使用会话工厂的班级是

package com.csc.student.DAO;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.csc.StudentAdmission.Student;


public class StudentInfo {
    SessionFactory sessionFactory;

    public StudentInfo() {
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Student processLoginForm(String userName, String password) {
        System.out.println("AlokAlokAlokAlokAlok");
        System.out.println(userName+" " + password);
        System.out.println(userName+" " + password); //till here it print in the console

        Session session = getSessionFactory().openSession();

          System.out.println("AlokAlokAlokAlokAlok");//it does not print
        session.beginTransaction();
        String hql = "FROM Student WHERE userName='" + userName
                + "' and password='" + password + "'";
        System.out.println(userName+" " + password);
        System.out.println("SoniSoniSoniSoni");
        System.out.println(userName+" " + password);
        System.out.println(userName+" " + password);
        System.out.println(userName+" " + password);

        Query query = session.createQuery(hql);

        @SuppressWarnings("unchecked")
        List<Student> results = query.list();

        if (!results.isEmpty()) {
            Student student = new Student();
            student = results.get(0);
            System.out.println(student.getFirstName());
            System.out
                    .println("jldfhgjklsdfhg;aoirygfuaq weoprrrrrrrrrvtbgqwery ");
            return student;
        } else
            return null;
    }
}

servlet.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.csc.StudentAdmission" />
    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>
    <bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name ="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/hibernatedb;create=true" />
        <property name="username" value="postgres" />
        <property name="password" value="root" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.csc.student.DAO"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> 
            </props>
        </property>
    </bean>

</beans>

我已经从停止执行的地方评论过了。一切都很好,但执行后它会在我通过getter获取sessionFactory的行上抛出NULLPointer异常。 this is directory structure of my project.StudentAdmissionController.java is my controller

StudentAdmissionController.java是我的控制器,它调用DAO类。 我的web.xml是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
  <display-name>SpringMVC</display-name>
  <servlet>
      <servlet-name>spring-dispatcher</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
   </servlet>

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

这是调用方法ProcessLoginForm方法

的类
package com.csc.StudentAdmission;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.csc.student.DAO.StudentInfo;

@Controller
public class StudentAdmissionController {

    @RequestMapping(value="/admissionFrom.html", method=RequestMethod.GET)
    public ModelAndView getAdmissionFrom(){
        ModelAndView model=new ModelAndView("AdmissionForm");
        return model;
    }


    @ModelAttribute
    public void addingCommonObjects(Model model){
        model.addAttribute("msg", "National Institue of Technology, India");        
    }

    @RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
    public ModelAndView submitAdmissionFrom(@ModelAttribute("student") Student student, BindingResult result) {
        ModelAndView model;
        if (result.hasErrors()) {
            model = new ModelAndView("AdmissionForm");
            return model;
        }

        System.out.println(student.getFirstName());
        System.out.println(student.getFirstName());
        System.out.println(student.getFirstName());
        System.out.println("jksdfhjksdfhsugasdhljkawe");
        System.out.println("Alok kkjkjkja Soni soni");
        StudentInfo studentInfo = new StudentInfo();



        if (studentInfo.saveStudentInfoIntoDB(student)) {
            model = new ModelAndView("AdmissionSuccess");
        } else {
            model = new ModelAndView("AdmissionForm");
            model.addObject("msg", "UserName or roll no are already existing");
        }
        return model;

    }

    @RequestMapping(value="/SpringMVC/Login.html", method=RequestMethod.GET)
    public ModelAndView loginForm(){
        ModelAndView model=new ModelAndView("LoginPage");
        return model;
    }

    @RequestMapping(value="/LoginForExistingUser.html", method=RequestMethod.POST)
    public ModelAndView loginForExistingUser(@RequestParam("userName") String userName, @RequestParam("password") String password){

        StudentInfo studentInfo = new StudentInfo();
        System.out.println(userName + " "+ password);
        System.out.println("djfkghs hgd;fg sdfgjh;sdfg ghsldf");

        Student student = studentInfo.processLoginForm(userName, password);
        ModelAndView model;



        if(student!=null){
            model=new ModelAndView("AdmissionSuccess");
            model.addObject("student", student);
        }
        else
        {
            model=new ModelAndView("LoginPage");
            model.addObject("message", "Incorrect user name or password");
        }
        return model;
    }
}

2 个答案:

答案 0 :(得分:1)

@Repository课程上添加StudentInfo注释。这应该有用。

根据补充信息:

StudentInfo studentInfo = new StudentInfo();

将创建一个不由spring管理的bean实例。就像你在sessionfactory在控制器创建实例

中所做的那样
@Autowired
StudentInfo studentInfo 

 @Autowired
 private void setStudentInfo (StudentInfo student)
 {
  studentInfo = student;
 }

另外阅读here关于托管beean的不同之处。

答案 1 :(得分:1)

你需要做两件事:

  1. 将@Repository添加到StudentInfo类
  2. 更新组件扫描配置以扫描“com.csc.student.DAO”
  3. 注意:组件扫描用于自动检测使用@Component @Repository,@ Service或@Controller注释的类