使用spring时,无法注入(提示:java.lang.NullPointerException)

异常信息:
[code="java"]
hibernateTemplate: null
2008-11-5 11:02:44 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet dispatcherServlet threw exception
java.lang.NullPointerException
at com.test.dao.jdbc.UserDAO.insert(UserDAO.java:11)
at com.test.controller.LoginController.onSubmit(LoginController.java:21)
at org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:408)
at org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:380)
at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:267)
at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:250)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:820)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:755)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:78)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:595)
[/code]
web.xml:
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>
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"
version="2.4">

<display-name>TestDemo</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.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>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>


[/code]

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

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=test"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mappingResources">
        <list>
            <value>com/test/domain/User.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
        </props>
    </property>
</bean>

<bean id="userDAO" class="com.test.dao.jdbc.UserDAO">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>


[/code]

dispatcherServlet-servlet.xml:
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">





<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="/login.do">loginController</prop>
        </props>
    </property>
</bean>

<bean id="loginController" class="com.test.controller.LoginController">
    <property name="successView" value="/admin/success"></property>
    <property name="formView" value="/admin/login"></property>
</bean>


[/code]

IUserDAO.java:
[code="java"]
package com.test.dao;

import com.test.domain.User;

public interface IUserDAO {

public void insert(User user);
public User find(Integer id);

}
[/code]

BaseDao.java:
[code="java"]
package com.test.dao.jdbc;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseDao extends HibernateDaoSupport {
public int getTotal(String hql) {
try {
List result = this.getHibernateTemplate().find(hql);
if (null != result && !result.isEmpty()) {
return ((Integer) result.get(0)).intValue();
} else {
return 0;
}
} catch (DataAccessException e) {
return 0;
}
}
}
[/code]

UserDAO.java:
[code="java"]
package com.test.dao.jdbc;

import java.util.*;
import com.test.dao.IUserDAO;
import com.test.domain.User;

public class UserDAO extends BaseDao implements IUserDAO {

public void insert(User user) {
    System.out.println("hibernateTemplate: " + this.getHibernateTemplate());
    this.getHibernateTemplate().update("INSERT INTO USERPASS (USERNAME, PASSWORDS) VALUES ('" + user.getUserName() +"', '" + user.getPassword() + "')");
}

public User find(Integer id) {
    List rows = this.getHibernateTemplate().find("SELECT * FROM USERPASS WHERE ID=" + id.intValue());
    Iterator it = rows.iterator();
    if(it.hasNext()) {
        Map userMap = (Map)it.next();
        User user = new User();
        user.setUserName(userMap.get("USERNAME").toString());
        user.setPassword(userMap.get("PASSWORDS").toString());
        return user;
    }
    return null;
}

}
[/code]

LoginController.java:
[code="java"]
package com.test.controller;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.*;

import com.test.domain.User;
import com.test.dao.*;
import com.test.dao.jdbc.*;

public class LoginController extends SimpleFormController {

public LoginController() {
    setCommandClass(User.class);
}

protected ModelAndView onSubmit(Object commond) throws Exception {
    User user = (User)commond;
    String name = user.getUserName();
    String pass = user.getPassword();
    IUserDAO userDAO = new UserDAO();
    userDAO.insert(user);
    user = userDAO.find(new Integer(1));
    if(name.equals(user.getUserName()) && pass.equals(user.getPassword())) {
        return new ModelAndView(getSuccessView(), "user", user.getUserName());
    } else {
        return new ModelAndView(getFormView());
    }
}

}
[/code]

3个回答

你的LoginController应该这样写:
[code="java"]
public class LoginController extends SimpleFormController {

private IUserDAO userDAO;  

 public LoginController() {  
     setCommandClass(User.class);  
 }  

 protected ModelAndView onSubmit(Object commond) throws Exception {  
     User user = (User)commond;  
     String name = user.getUserName();  
     String pass = user.getPassword();  
    //IUserDAO userDAO = new UserDAO();  // 注意:这条是注释掉的
     userDAO.insert(user);  
     user = userDAO.find(new Integer(1));  
     if(name.equals(user.getUserName()) && pass.equals(user.getPassword())) {  
         return new ModelAndView(getSuccessView(), "user", user.getUserName());  
     } else {  
         return new ModelAndView(getFormView());  
     }  
 }  

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

}
[/code]
配置:
[code="java"]








[/code]

问题出在LoginController中, [code="java"]# IUserDAO userDAO = new UserDAO();

userDAO.insert(user); [/code]你这里是new出来的, 在你的BaseDao中, 这一句:

[code="java"]
List result = this.getHibernateTemplate().find(hql);

[/code]
this.getHibernateTemplate()得到的是null, 所以NullPointerException.

[code="java"]at com.test.dao.jdbc.UserDAO.insert(UserDAO.java:11) [/code]
应该是你的UserDAO没注入吧

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐