getCurrentSession NullPointerException

时间:2014-06-24 11:12:14

标签: java spring hibernate servlets tomcat7

堆栈跟踪:

java.lang.NullPointerException
at de.mail.HibernateUtil.getSession(HibernateUtil.java:30)
at de.mail.gui.LoginServlet.doPost(LoginServlet.java:55)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

的HibernateUtil:

public abstract class HibernateUtil extends HttpServlet{

private static final long serialVersionUID = -1850678939342717642L;

@Autowired
private SessionFactory sessionFactory;

/**
 * Gibt die derzeitige Session zurück
 * 
 * @return derzeitige Session
 * @throws HibernateException
 */
public Session getSession() {
    return sessionFactory.getCurrentSession();
}
}

LoginServlet:

@Component
public class LoginServlet extends HibernateUtil {

/**
 * 
 */
private static final long serialVersionUID = -776218596462464850L;
private static final Log LOG = LogFactory.getLog(LoginServlet.class);
private static final int HEX_FF = 0xFF;

/**
 * Bearbeitet den Loginversuch<br />
 * Es werden die eingegebenen Daten ausgelesen. Aus dem Passwort wird ein Hash-Wert generiert, der mit dem Datenbankeintrag mit dem
 * passenden Usernamen verglichen wird. Stimmt alles &uumlberein wird auf die main.jsp weitergeleitet. Im Fehlerfall wird zur&uumlck auf
 * die login.jsp verwiesen.
 * 
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 * @param response der HttpResponse
 * @param request der HttpRequest
 * @throws ServletException ex
 * @throws IOException ex
 */
@Override
@Transactional
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

    if (!"Registrieren".equals(request.getParameter("register"))) {

        final Session session = getSession();

        // Generiert einen HashWert aus dem eingegebenen Passwort
        try {
            final byte[] pwBytes = request.getParameter("password").getBytes();
            final MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(pwBytes);
            final byte[] messageDigest = algorithm.digest();

            final StringBuffer hexString = new StringBuffer();

            for (byte digest : messageDigest) {
                hexString.append(Integer.toHexString(HEX_FF & digest));
            }

            final LoginDAO dao = new LoginDAO();
            final List<UserVO> list = dao.checkLogin(request, session);

            final UserVO userVO = list.get(0);

            if (userVO.getPassword().equals(hexString.toString())) {

                request.getSession().setAttribute("userid", userVO.getId());
                final RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
                dispatcher.forward(request, response);

            } else {

                final RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
                dispatcher.forward(request, response);
            }

        } catch (NoSuchAlgorithmException nsax) {
            LOG.debug("Keine MessageDigestSpi fuer den entsprechenden Alogrithmus gefunden");

        } catch (NullPointerException npx) {
            final RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
            dispatcher.forward(request, response);

        } catch (IndexOutOfBoundsException ioobx) {
            final RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
            dispatcher.forward(request, response);
        }
    } else {
        final RequestDispatcher dispatcher = request.getRequestDispatcher("register.jsp");
        dispatcher.forward(request, response);
    }
}

/**
 * Tut nix besonders. Leiet an die doPost-Methode weiter
 * 
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 * @param response der HttpResponse
 * @param request der HttpRequest
 * @throws ServletException ex
 * @throws IOException ex
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
}
}

带有hibernate实现的context.xml:

<!-- Component Scans -->
<context:component-scan base-package="de.mail"></context:component-scan>
<!-- Datenbank -->

<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
    <property name="driverClass" value="org.postgresql.Driver" />
    <property name="jdbcUrl" value="something" />
    <property name="maxPoolSize" value="1" />
    <property name="properties">
        <props>
            <prop key="user">postgres</prop>
            <prop key="password">***</prop>
            <prop key="characterEncoding">UTF-8</prop>
            <!-- Properties sind nur notwendig, wenn man mal SSL für die DB-Verbindung 
            braucht (auch in der properties entkommentieren) -->
            <!-- <prop key="ssl">${db.ssl}</prop> <prop key="sslfactory">${db.sslfactory}</prop> -->
        </props>
    </property>
</bean>

<alias name="c3p0DataSource" alias="dataSource" />

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
    <property name="nestedTransactionAllowed" value="true" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" destroy-method="destroy">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>                
        </props>
    </property>     
    <property name="annotatedPackages">
      <list>
        <value>de.mail</value>
        <value>de.mail.data.dao</value>
        <value>de.mail.vo</value>
        <value>de.mail.gui</value>
      </list>
    </property>
    <property name="annotatedClasses">        
      <list>
        <value>de.mail.data.vo.UserVO</value>
        <value>de.mail.data.vo.FilterVO</value>
        <value>de.mail.data.vo.ResultVO</value>
        <value>de.mail.data.dao.ActionDAO</value>
        <value>de.mail.HibernateUtil</value>
        <value>de.mail.FilterJob</value>
        <value>de.mail.gui.ActionServlet</value>
        <value>de.mail.gui.CreateServlet</value>
        <value>de.mail.gui.DeleteServlet</value>
        <value>de.mail.gui.EditServlet</value>
        <value>de.mail.gui.FormServlet</value>
        <value>de.mail.gui.InitServlet</value>
        <value>de.mail.gui.LoginServlet</value>
        <value>de.mail.gui.LogoutServlet</value>
        <value>de.mail.gui.RegistrationServlet</value>
      </list>
    </property>

</bean>

到目前为止,感谢您的回答!我真的很喜欢他们。

我编辑了帖子并添加了更新的课程。 我仍然得到NullPointerException ...我真的没有得到它。 我在这里缺少什么?

我想我发现了自己的问题,但现在我面临一个新问题:     注释类型Transactional

的属性传播未定义

我该如何解决这个问题? - &GT;修复:我导入了错误的包!必须导入 org.springframework.transaction.annotation.Propagation

现在我又得到了NullPointerException。我的猜测是, SessionFactory == null。但为什么呢?

4 个答案:

答案 0 :(得分:3)

@Autowired
private static SessionFactory sessionFactory;

检查一下。你不能在Spring中自动装配静态字段

答案 1 :(得分:0)

使HibernateUtil的staticFactory和getSession成为非静态成员; @Autowire不适用于静态字段。

HibernateUtil不是Spring bean;因此,您的sessionFactory字段上的@Autowire注释将不会继续。

您可以在context.xml中将HibernateUtil配置为spring bean,或者使用@Component,@ Service或@Repository注释(哪一个适合...)注释该类。如果使用注释,请确保在context.xml中启用组件扫描到适当的包。现在你的HibernateUtil将成为一个Spring bean,并准备注入它的依赖。

在LoginServlet中,将HibernateUtil作为字段并使用@Autowire进行注释。在LoginServlet的init方法中添加以下代码,因此spring将负责将hibernateutil注入登录servlet。

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

答案 2 :(得分:0)

可能很愚蠢,但是你确定要将这些类添加到component-scan指令中以便拾取注释吗?

<context:component-scan base-package="de.mail.data.vo,com.blah" />

答案 3 :(得分:0)

由于几个问题我决定改造整个项目,所以这里的问题可以关闭。感谢所有答案,他们正在帮助我!