日期:2014-05-18  浏览次数:20847 次

在controller中调用dao 显示dao为空 这事为什么(spring+HIbernate))
做个小练习 用hibernate+spring+springmvc做一个登录界面 
在登录的controller中想调用 dao来进行查询 结果测试的时候显示dao的空指针一场 
已经在loginController中设置了dao的setter/getter方法 可是依然报空
下面是代码

loginController.java 

public class loginController {
private userDaoImpl userdaoimpl;


@RequestMapping("/login.do")
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response){

//userdaoimpl = new UserDaoImpl();

ModelAndView mdv = new ModelAndView();


String username ="111";
String password ="111";
if(userdaoimpl == null){
System.out.print("userdaoimpl is null");
}

List<User> list = userdaoimpl.findUserByUsername(username);

if(list.isEmpty()){
mdv.setViewName("login1");
}

//System.out.print(username+","+password);
else if(list.get(0).getPassword().equals(password)){
mdv.addObject("username",username);
mdv.addObject("password",password);
mdv.setViewName("loginSuccess");
}

if(list.isEmpty()){
System.out.print("list is null");
}
else{
User user = list.get(0);
System.out.println("hello"+user.getUsername());
                mdv.setViewName("loginSuccess");
}


return mdv;
}

public void setUserDaoImpl(userDaoImpl userdaoimpl){
this.userdaoimpl = userdaoimpl;
}

public userDaoImpl getUserDaoImpl(){
return this.userdaoimpl;
}
}

userDaoImpl代码

public class userDaoImpl extends BaseDao implements UserDao{

private HibernateTemplate hibernatetemplate;

@SuppressWarnings("unchecked")
@Override
public List<User> findUserByUsername(String username) {
// TODO Auto-generated method stub


List user = hibernatetemplate.find("from User u  where u.username = ?", username);
return user;
}

}

applicatonContext的后几行配置bean的代码:

<bean id="userdao" class="com.lightblog.dao.userDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="loginController" class="com.lightblog.controller.loginController">
<property name="userdao" ref="userdao" />
</bean>

异常代码

exception 

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


root cause