在Web应用程序中使用Hibernate和Spring的问题

时间:2011-02-22 14:59:29

标签: java hibernate spring

我正在尝试使用NullPointerException getCurrentSession()

 java.lang.NullPointerException
 servlets.ControlServlet.doPost(ControlServlet.java:46)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

我使用Tomcat 5.5 index.jsp页面:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<%@ page import="java.util.List" %>
<%@ page import="data.Singer" %>
<jsp:useBean id="singer" class="data.Singer" scope="session"/> 
<jsp:setProperty name="singer" property="*" />

<form action="ControlServlet" method="POST">
    <form method=“POST”>
    Name:<br /> 
    <input type=“text” name="name" /><br />
    Type:<br />
    <input type=“text” name="type" /><br />
    <input type="submit" name="Add song" value="Add song">
    <input type="submit" name="save" value="Save" /><br><br>
<input type ="submit" name="values" value="Get values" >
</form>
</body>
</html>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>webproject</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/beans.xml, /WEB-INF/conf.xml, /WEB-INF/singers.hbm.xml, /WEB-INF/songs.hbm.xml, /WEB-INF/singerbeans.xml, /WEB-INF/songbeans.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>context</servlet-name>
        <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>*.*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/beans.xml, /WEB-INF/conf.xml, /WEB-INF/singers.hbm.xml, /WEB-INF/songs.hbm.xml, /WEB-INF/singerbeans.xml, /WEB-INF/songbeans.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>2</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>2</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet>
        <description>
    </description>
        <display-name>ControlServlet</display-name>
        <servlet-name>ControlServlet</servlet-name>
        <servlet-class>servlets.ControlServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ControlServlet</servlet-name>
        <url-pattern>/ControlServlet</url-pattern>
    </servlet-mapping>


</web-app>

ControlServlet.java

public class ControlServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Autowired
    private SingerDao singerdao; 
    public SingerDao getSingerDao() {
        return singerdao;
    }

    public void setSingerDao(SingerDao singerdao) {
        this.singerdao = singerdao;
    }

    public ControlServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (request.getParameter("values") != null) {
            response.getWriter().println(singerdao.getDBValues());
        }
    }

}

和SingerDao.java

public class SingerDao implements SingerDaoInterface {
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public List getDBValues() {
        Session session = getCurrentSession();
        List<Singer> singers = session.createCriteria(Singer.class).list();
        return singers;
    }

    private org.hibernate.classic.Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public void updateSinger(Singer singer) {
        Session session = getCurrentSession();
        session.update(singer);
    }

    public Singer getSinger(int id) {
        Singer singer = null;
        Session session = getCurrentSession();
        singer = (Singer) session.load(Singer.class, id);
        return singer;

    }

    public void deleteSinger(Singer singer) {
        Session session = getCurrentSession();
        session.delete(singer);
    }

    public void insertRow(Singer singer) {
        Session session = getCurrentSession();
        session.save(singer);
    }



}

在简单的Java Project中,它运行正常。我认为sessionFactory不会自动装配,但为什么呢? 谢谢大家。

2 个答案:

答案 0 :(得分:2)

您不能在普通servlet中使用@Autowired,因为它们不受Spring管理。

但是,你可以使用以下技巧来手动启动servlet的自动装配:

public class ControlServlet extends HttpServlet {
    @Autowired
    private SingerDao singerdao; 

    public void init(ServletConfig cfg) {
        super.init(cfg);
        WebApplicationContextUtils
            .getWebApplicationContext(cfg.getServletContext())
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    } 
    ...
}

另外,正如评论中所建议的那样,因为你的设置中已经有了Spring MVC的DispatcherServlet,所以最好将ControlServlet的功能实现为Spring MVC控制器而不是servlet(除非你有有充分理由将其作为servlet)。

答案 1 :(得分:0)

堆栈跟踪告诉您NPE发生在ControlServlet类的第46行,而不是方法doPost。这肯定是您尝试调用singerdao对象的方法的行。

所以这是没有注入的属性。并不奇怪,因为Servlet是由Web容器实例化的,而不是Spring实例化的。 Spring对这个servlet一无所知,也不能向它注入任何东西。