尝试访问dwr函数中的模型类时获取Null指针异常

时间:2014-05-17 10:43:01

标签: spring hibernate hibernate-mapping

    My SessionFactory object is @Autowired

    package com.ravi.dao.daoImpl;

    import java.util.List;

    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;

    import com.ravi.dao.UserDao;
    import com.ravi.model.User;

    @Repository("userDao")
    public class UserDaoImpl implements UserDao {

        @Autowired
        private SessionFactory sessionFactory;


        @SuppressWarnings("unchecked")
        public List<User> listUsers() 
        {
            System.out.println("UserDaoImpl - listUsers");
            return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
        }
        @Override
        public void saveUser(User user) 
        {
            System.out.println("UserDaoImpl - saveUser");
            sessionFactory.getCurrentSession().saveOrUpdate(user);
        }

        @SuppressWarnings("unchecked")
        @Override
        public List<User> getUserByUserEmail(String userEmail) 
        {
            System.out.println("UserDaoImpl - getUserByUserEmail");
            return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list();
        }

        @SuppressWarnings("unchecked")
        @Override
        public List<User> validateLoginUser(String userEmail, String password) 
        {
            System.out.println("userEmail -- "+userEmail+" password --"+password);
            System.out.println("UserDaoImpl - validateLoginUser");
            return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail and password=:password").setString("userEmail", userEmail).setString("password",password).list();
        }
    }


    i create on dwr function which is below.

    package com.ravi.dwr;

    import java.util.List;
    import com.ravi.dao.daoImpl.UserDaoImpl;
    import com.ravi.model.User;


    public class ForgotPwd 
    {
        public void sendMail(String EmailId)
        {
            System.out.println("DWR Called.");

            UserDaoImpl userDaoImpl=new UserDaoImpl();
            List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
            User user=lstUser.get(0);

            System.out.println("DWR Called.-- userEmail :"+user.getUserEmail());    
        }
    }
    when i want to try to print userEmail . null pointer exception is generated @ return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list(); this point.


    my spring-servlet.xml cofiguration.


    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

        <context:property-placeholder location="classpath:jdbc.properties" />
        <context:component-scan base-package="com.ravi"/>

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

        <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/view/" />
            <property name="suffix" value=".jsp" />
        </bean>

        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${database.driver}" />
            <property name="url" value="${database.url}" />
            <property name="username" value="${database.user}" />
            <property name="password" value="${database.password}" />
        </bean>

        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <!--  <bean id="sessionFactory"  -->
    <!--            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
            <property name="dataSource" ref="dataSource" />
            <property name="annotatedClasses">
                <list>
                    <value>com.ravi.model.User</value>
                    <value>com.ravi.model.Language</value>
                    <value>com.ravi.model.Questions</value>
                    <value>com.ravi.model.QuestionOptions</value>
                    <value>com.ravi.model.Admin</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                </props>
            </property>
        </bean>

        <bean id="hibernateTransactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="SessionFactory" ref="sessionFactory" />
        </bean>

        <bean id="messageSource"
            class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basename" value="/WEB-INF/messages" />
        </bean>

    in my project i used Annotation. is there any way to get user model data in dwr function.
    or is there any process which automatically initialized (inject) when i try to use DAO class)

     i don't want to remove @Autowired annotation in sessionFactory object. so please suggest me the best way to access or configure dwr function. other way i tried without using @Autowired annotation but in that case i have to entry all bean class in my spring-servlet.xml and also configure. hibernate.cfg.xml file.

 in my project i used Annotation. is there any way to get user model data in dwr function.
    or is there any process which automatically initialized (inject) when i try to use DAO class)


   here i explain whole process. thank you in advance.
   below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
    on more time i cleared that this is DWR function. which try to access sessionFactory instance. 
without interacting controller.


UserLoginController --> showUserLogin 
INFO   (org.directwebremoting.log.startup:157) - Starting: DwrServlet v3.0.0-RC2-final-312 on Apache Tomcat/7.0.50 / JDK 1.7.0_10 from Oracle Corporation at `enter code here`/OnlineQuestion
DWR Called.
INFO   (org.directwebremoting.log.accessLog:427) - Method execution failed: 
java.lang.NullPointerException
    at com.ravi.dwr.ForgotPwd.sendMail(ForgotPwd.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
    at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
    at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
    at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
    at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
    at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
    at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChai

这里我解释整个过程。先感谢您。        当我尝试访问userDaoImpl函数时生成以下错误。错误显示会话工厂对象未初始化。         在更多的时间我清除这是DWR功能。试图访问sessionFactory实例。     没有交互控制器。

1 个答案:

答案 0 :(得分:0)

假设您要将Spring MVC与DWR一起使用,请尝试以下代码:

WEB-INF / web.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

WEB-INF /弹簧servlet.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<beans
  ...
  xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
  ...
  http://www.directwebremoting.org/schema/spring-dwr
  http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
  <dwr:controller id="dwrController" />
  <dwr:annotation-scan base-package="com.ravi.dwr" />
  <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="alwaysUseFullPath" value="true" />
    <property name="mappings">
      <props>
        <prop key="/dwr/**/*">dwrController</prop>
      </props>
    </property>
  </bean>

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

</beans>

ForgotPwd.java

package com.ravi.dwr;

...
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
...

@RemoteProxy
public class ForgotPwd {

  @Autowired
  private UserDaoImpl userDaoImpl;

  ...

  @RemoteMethod
  public void sendMail(String EmailId) {
    System.out.println("DWR Called.");
    List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
    ...
  }

  ...
}