论坛首页 入门技术论坛

求助!!action里调用dao出现空指针错误,发现dao为null,不知为何?

浏览 11173 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-05-28  
不好意思 代码比较多,不过很容易看懂,userDAO注入进来为null,new一个userDAO,提示操作失败,说dao有问题,这几写个测试类,dao却没有问题
Login.javapackage action;


import java.util.Iterator;
import java.util.List;
import java.util.Map;
import dao.user.UserDAO;
import domain.user.User;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;

public class Login  implements Action {

private User user = new User();
private UserDAO userDAO;
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("Start execute......。。。。。。。。。。。。。。");
System.out.println("User="+user.getName());
if(user.getName()==null||user.getName().equals("")||user.getPassword()==null||user.getPassword().equals("")){
return INPUT;
}else{
    List l = userDAO.findByProperty("name", user.getName());//就在这行出现空指针错误,userDAO为null
    Iterator i = l.iterator();
    User users=null;
    while(i.hasNext()){
     users = (User)i.next();
     System.out.println("User="+users.getName());
    }
if(user.getName().equals(users.getName())){
return SUCCESS;
}
return null;
}
}

public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}

public UserDAO getUserDAO() {
return userDAO;
}

public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}

}
UserDAO.java
package dao.user;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import domain.user.User;;

/**
* Data access object (DAO) for domain model class user.
* @see .user
* @author MyEclipse - Hibernate Tools
*/
public class UserDAO extends HibernateDaoSupport implements IBaseHibernateDAO {

    private static final Log log = LogFactory.getLog(UserDAO.class);
    private LocalSessionFactoryBean sessionFactory;

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

/* (non-Javadoc)
* @see dao.a#save(domain.user.User)
*/
    public void save(User transientInstance) {
        log.debug("saving user instance");
        try {
        getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
       
    public List findByProperty(String propertyName, Object value) {
        log.debug("finding User instance with property: " + propertyName
              + ", value: " + value);
        try {
           String queryString = "from User as model where model."
                 + propertyName + "= ?";
     return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
           log.error("find by property name failed", re);
           throw re;
        }
   }
}
UserDAOTest.java userDAO的测试类,结果没问题
package testConnection;

import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import dao.user.UserDAO;
import domain.user.User;;

public class UserDAOTest {

public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
UserDAO userDAO =(UserDAO)context.getBean("userDAO");
logger.debug("初始化成功");
System.out.print("初始化成功");
List l = userDAO.findByProperty("name", "ray");
Iterator i = l.iterator();
while(i.hasNext()){
User u = (User)i.next();
System.out.println(u.getPassword());
}
}

}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/init.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName">
            <value>${dataSource.driverClassName}</value>
        </property>
        <property name="url">
            <value>${dataSource.url}</value>
        </property>
        <property name="username"><value>${dataSource.username}</value></property>
        <property name="password"><value>${dataSource.password}</value></property>
    </bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
        </props>
    </property>
    <property name="mappingResources">
        <list>
            <!-- 加u-28803 映u23556 文u20214  -->
            <value>User.hbm.xml</value>
           
        </list>
    </property>
</bean>

<bean id="login" class="action.Login">
        <property name="userDAO">
            <ref bean="userDAO" />
        </property>    
    </bean>
   <bean id="userDAO" class="dao.user.UserDAO" dependency-check="all">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
      
    </bean>
</beans>
xwork.xml
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN" "http://www.opensymphony.com/xwork/xwork-1.0.dtd">

<xwork>
    <include file="webwork-default.xml"/>
    <include file="config-browser.xml"/>
    <package name="default" extends="webwork-default">
    <action name="login" class="action.Login">
<result name="success" type="dispatcher">
<param name="location">/success.jsp</param>
</result>
<result name="input" type="dispatcher">
<param name="location">/success.jsp</param>
</result>
<interceptor-ref name="params"/>
</action>
    </package>
</xwork>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>webwork</servlet-name>
<servlet-class>com.opensymphony.webwork.dispatcher.ServletDispatcher</servlet-class>
</servlet>

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

<taglib>
<taglib-uri>webwork</taglib-uri>
<taglib-location>/WEB-INF/taglib.tld</taglib-location>
</taglib>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
   发表时间:2007-05-28  
userDao为空,貌似没注入?Debug一下?
0 请登录后投票
   发表时间:2007-05-28  
jessdy 写道
userDao为空,貌似没注入?Debug一下?
确实没注入进去 不知道为什么?而且new一个userDAO的话,提示dao里的方法有问题,可是写了个测试类,dao方法没问题,很是不解
0 请登录后投票
   发表时间:2007-05-28  
好像是applicationContext.xml没有被加载进去,在action里
/*ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAO userDAO =(UserDAO)context.getBean("userDAO"); */
显示加载下就可以了,但我在web.xml里已经用个监听器加载了,
2007-5-28 13:46:36 org.apache.coyote.http11.Http11AprProtocol init
信息: Initializing Coyote HTTP/1.1 on http-8080
2007-5-28 13:46:36 org.apache.coyote.ajp.AjpAprProtocol init
信息: Initializing Coyote AJP/1.3 on ajp-8009
2007-5-28 13:46:36 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1219 ms
2007-5-28 13:46:36 org.apache.catalina.core.StandardService start
信息: Starting service Catalina
2007-5-28 13:46:36 org.apache.catalina.core.StandardEngine start
信息: Starting Servlet Engine: Apache Tomcat/5.5.17
2007-5-28 13:46:36 org.apache.catalina.core.StandardHost start
信息: XML validation disabled
2007-5-28 13:46:38 org.apache.catalina.core.ApplicationContext log
信息: org.apache.webapp.balancer.BalancerFilter: init(): ruleChain: [org.apache.webapp.balancer.RuleChain: [org.apache.webapp.balancer.rules.URLStringMatchRule: Target string: News / Redirect URL: http://www.cnn.com], [org.apache.webapp.balancer.rules.RequestParameterRule: Target param name: paramName / Target param value: paramValue / Redirect URL: http://www.yahoo.com], [org.apache.webapp.balancer.rules.AcceptEverythingRule: Redirect URL: http://jakarta.apache.org]]
2007-5-28 13:46:38 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2007-5-28 13:46:38 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2007-5-28 13:46:38 org.apache.catalina.loader.WebappClassLoader validateJarFile
信息: validateJarFile(C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\note\WEB-INF\lib\j2ee.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
2007-5-28 13:46:38 org.apache.catalina.loader.WebappClassLoader validateJarFile
信息: validateJarFile(C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\note\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
[INFO] 2007-05-28 13:46:39,515 org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
[INFO] 2007-05-28 13:46:39,531 org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/note] - Loading Spring root WebApplicationContext
[INFO] 2007-05-28 13:46:39,828 org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
[INFO] 2007-05-28 13:46:41,125 org.springframework.web.context.support.XmlWebApplicationContext - Bean factory for application context [Root WebApplicationContext]: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [dataSource,sessionFactory,userDAO,login]; root of BeanFactory hierarchy
[INFO] 2007-05-28 13:46:41,187 org.springframework.web.context.support.XmlWebApplicationContext - 4 beans defined in application context [Root WebApplicationContext]
[INFO] 2007-05-28 13:46:41,218 org.springframework.core.CollectionFactory - JDK 1.4+ collections available
[INFO] 2007-05-28 13:46:41,250 org.springframework.web.context.support.XmlWebApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@15ad1da]
[INFO] 2007-05-28 13:46:41,265 org.springframework.web.context.support.XmlWebApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@1ca1a68]
[INFO] 2007-05-28 13:46:41,296 org.springframework.ui.context.support.UiApplicationContextUtils - Unable to locate ThemeSource with name 'themeSource': using default [org.springframework.ui.context.support.ResourceBundleThemeSource@15d4273]
[INFO] 2007-05-28 13:46:41,312 org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in factory [org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [dataSource,sessionFactory,userDAO,login]; root of BeanFactory hierarchy]
[INFO] 2007-05-28 13:46:41,593 org.hibernate.cfg.Environment - Hibernate 3.0.5
[INFO] 2007-05-28 13:46:41,625 org.hibernate.cfg.Environment - hibernate.properties not found
[INFO] 2007-05-28 13:46:41,625 org.hibernate.cfg.Environment - using CGLIB reflection optimizer
[INFO] 2007-05-28 13:46:41,640 org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
[INFO] 2007-05-28 13:46:42,625 org.hibernate.cfg.HbmBinder - Mapping class: domain.user.User -> user
[INFO] 2007-05-28 13:46:42,718 org.springframework.orm.hibernate3.LocalSessionFactoryBean - Building new Hibernate SessionFactory
[INFO] 2007-05-28 13:46:42,718 org.hibernate.cfg.Configuration - processing extends queue
[INFO] 2007-05-28 13:46:42,718 org.hibernate.cfg.Configuration - processing collection mappings
[INFO] 2007-05-28 13:46:42,718 org.hibernate.cfg.Configuration - processing association property references
[INFO] 2007-05-28 13:46:42,734 org.hibernate.cfg.Configuration - processing foreign key constraints
[INFO] 2007-05-28 13:46:42,968 org.hibernate.connection.ConnectionProviderFactory - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
[INFO] 2007-05-28 13:46:43,546 org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.0.22-community-nt
[INFO] 2007-05-28 13:46:43,546 org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.1.10 ( $Date: 2005/05/19 15:52:23 $, $Revision: 1.1.2.2 $ )
[INFO] 2007-05-28 13:46:43,640 org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
[INFO] 2007-05-28 13:46:43,671 org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
[INFO] 2007-05-28 13:46:43,687 org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
[INFO] 2007-05-28 13:46:43,703 org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
[INFO] 2007-05-28 13:46:43,703 org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
[INFO] 2007-05-28 13:46:43,703 org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
[INFO] 2007-05-28 13:46:43,703 org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
[INFO] 2007-05-28 13:46:43,718 org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
[INFO] 2007-05-28 13:46:43,718 org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
[INFO] 2007-05-28 13:46:43,718 org.hibernate.cfg.SettingsFactory - Connection release mode: on_close
[INFO] 2007-05-28 13:46:43,718 org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
[INFO] 2007-05-28 13:46:43,718 org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
[INFO] 2007-05-28 13:46:43,734 org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
[INFO] 2007-05-28 13:46:43,734 org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
[INFO] 2007-05-28 13:46:43,734 org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
[INFO] 2007-05-28 13:46:43,750 org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
[INFO] 2007-05-28 13:46:43,750 org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
[INFO] 2007-05-28 13:46:43,750 org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
[INFO] 2007-05-28 13:46:43,750 org.hibernate.cfg.SettingsFactory - Query cache: disabled
[INFO] 2007-05-28 13:46:43,750 org.hibernate.cfg.SettingsFactory - Cache provider: org.hibernate.cache.EhCacheProvider
[INFO] 2007-05-28 13:46:43,781 org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
[INFO] 2007-05-28 13:46:43,781 org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
[INFO] 2007-05-28 13:46:43,812 org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
[INFO] 2007-05-28 13:46:43,812 org.hibernate.cfg.SettingsFactory - Statistics: disabled
[INFO] 2007-05-28 13:46:43,812 org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
[INFO] 2007-05-28 13:46:43,812 org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
[INFO] 2007-05-28 13:46:44,218 org.hibernate.impl.SessionFactoryImpl - building session factory
[WARN] 2007-05-28 13:46:44,250 net.sf.ehcache.config.Configurator - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%205.5/webapps/note/WEB-INF/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
[INFO] 2007-05-28 13:46:45,484 org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
[INFO] 2007-05-28 13:46:45,484 org.hibernate.impl.SessionFactoryImpl - Checking 0 named queries
[INFO] 2007-05-28 13:46:45,609 org.springframework.web.context.ContextLoader - Using context class [org.springframework.web.context.support.XmlWebApplicationContext] for root WebApplicationContext
[INFO] 2007-05-28 13:46:45,625 org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 6110 ms
2007-5-28 13:46:45 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2007-5-28 13:46:45 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2007-5-28 13:46:46 org.apache.coyote.http11.Http11AprProtocol start
信息: Starting Coyote HTTP/1.1 on http-8080
2007-5-28 13:46:46 org.apache.coyote.ajp.AjpAprProtocol start
信息: Starting Coyote AJP/1.3 on ajp-8009
2007-5-28 13:46:46 org.apache.catalina.storeconfig.StoreLoader load
信息: Find registry server-registry.xml at classpath resource
2007-5-28 13:46:46 org.apache.catalina.startup.Catalina start
信息: Server startup in 10172 ms
这是信息,不知道为什么还是不行
0 请登录后投票
   发表时间:2007-06-15  
把<bean id="login" class="action.Login"> 这里改成
<bean id="login" class="action.Login" singleton="false>
注意一定是singleton="false",因为xwork的action是这样要求的.

还有你那个 <action name="login" class="action.Login"> 和application.xml不一致.

建议:<action name="login" class="action.Login"> 的 class="action.Login"> 就与<bean id="login" class="action.Login"> 的 <bean name="some-action">一致

0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics