Spring CRUD 应用程序:Servlet [dispatcherServlet] 的 Servlet.service():java.lang.NullPointerException]

Posted

技术标签:

【中文标题】Spring CRUD 应用程序:Servlet [dispatcherServlet] 的 Servlet.service():java.lang.NullPointerException]【英文标题】:Spring CRUD App: Servlet.service() for servlet [dispatcherServlet] : java.lang.NullPointerException] 【发布时间】:2019-03-23 09:20:34 【问题描述】:

我无法从 mysql 数据库获取员工数据。根据日志,我的 EmployeeServiceImpl.listEmployess 方法中的第 36 行存在问题。

日志:

2018-10-18 16:07:42.871 错误 1504 --- [nio-8090-exec-4] oaccC[.[.[/].[dispatcherServlet]:Servlet.service() 用于 servlet [dispatcherServlet]在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 java.lang.NullPointerException] 的根本原因

java.lang.NullPointerException: null

在 com.project.service.EmployeeServiceImpl.listEmployess(EmployeeServiceImpl.java:36) ~[classes/:na] com.project.service.EmployeeServiceImpl$$FastClassBySpringCGLIB$$c7d76ecc.invoke() ~[classes/:na] 在 org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] 在 com.project.service.EmployeeServiceImpl$$EnhancerBySpringCGLIB$$1390ca06.listEmployess() ~[classes/:na] 在 com.project.controller.EmployeeController.listEmployess(EmployeeController.java:34) ~[classes/:na] 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161] 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161] 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161] 在 java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]

EmployeeServiceImpl:

package com.project.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.dao.EmployeeDAO;
import com.project.entity.TEmployee;

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService 

private EmployeeDAO employeeDAO;

public void setEmployeeDAO(EmployeeDAO employeeDAO) 
    this.employeeDAO = employeeDAO;


@Override
@Transactional
public void addEmployee(TEmployee p) 
    this.employeeDAO.addEmployee(p);


@Override
@Transactional
public void updateEmployee(TEmployee p) 
    this.employeeDAO.updateEmployee(p);


@Override
@Transactional
public List<TEmployee> listEmployess() 
    return this.employeeDAO.listEmployess();


@Override
@Transactional
public TEmployee getEmployeeById(int employee_id) 
    return this.employeeDAO.getEmployeeById(employee_id);


@Override
@Transactional
public void removeEmployee(int employee_id) 
    this.employeeDAO.removeEmployee(employee_id);



员工服务:

package com.project.service;

import java.util.List;

import org.springframework.context.annotation.ComponentScan;

import com.project.entity.TEmployee;
@ComponentScan(basePackages= "com.project.*")
public interface EmployeeService 

public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int id);
public void removeEmployee(int id);


EmployeeDAO:

package com.project.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;

import com.project.entity.TEmployee;
@ComponentScan(basePackages= "com.project.*")
public interface EmployeeDAO 

public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int employee_id);
public void removeEmployee(int employee_id);

EmployeeDAOImpl:

package com.project.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.project.entity.TEmployee;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO 

private static final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf)
    this.sessionFactory = sf;


@Override
public void addEmployee(TEmployee p) 
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("TEmployee saved successfully, TEmployee Details="+p);


@Override
public void updateEmployee(TEmployee p) 
    Session session = this.sessionFactory.getCurrentSession();
    session.update(p);
    logger.info("TEmployee updated successfully, TEmployee Details="+p);


@SuppressWarnings("unchecked")
@Override
public List<TEmployee> listEmployess() 
    Session session = this.sessionFactory.getCurrentSession();
    List<TEmployee> EmployessList = session.createQuery("from TEmployee").list();
    for(TEmployee p : EmployessList)
        logger.info("TEmployee List::"+p);
    
    return EmployessList;


@Override
public TEmployee getEmployeeById(int employee_id) 
    Session session = this.sessionFactory.getCurrentSession();      
    TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
    logger.info("TEmployee loaded successfully, TEmployee details="+p);
    return p;


@Override
public void removeEmployee(int employee_id) 
    Session session = this.sessionFactory.getCurrentSession();
    TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
    if(null != p)
        session.delete(p);
    
    logger.info("TEmployee deleted successfully, TEmployee details="+p);



EmployeeController:

package com.project.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.project.entity.TEmployee;
import com.project.service.EmployeeService;

@ComponentScan(basePackages= "com.project.*")
@Controller
public class EmployeeController 

@Resource(name = "employeeService")
private EmployeeService employeeService;

@Autowired(required=true)
@Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService ps)
    this.employeeService = ps;


@RequestMapping(value = "/employess", method = RequestMethod.GET)
public String listEmployess(Model model) 
    model.addAttribute("employee", new TEmployee());
    model.addAttribute("listEmployess", this.employeeService.listEmployess());
    return "employee";


//For add and update person both
@RequestMapping(value= "/employee/add", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("employee") TEmployee p)

    if(p.getEmployeeID() == 0)
        //new person, add it
        this.employeeService.addEmployee(p);
    else
        //existing person, call update
        this.employeeService.updateEmployee(p);
    

    return "redirect:/employess";



@RequestMapping("/remove/employee_id")
public String removeEmployee(@PathVariable("employee_id") int employee_id)

    this.employeeService.removeEmployee(employee_id);
    return "redirect:/employess";


@RequestMapping("/edit/employee_id")
public String editEmployee(@PathVariable("employee_id") int employee_id, Model model)
    model.addAttribute("employee", this.employeeService.getEmployeeById(employee_id));
    model.addAttribute("listEmployess", this.employeeService.listEmployess());
    return "employee";



因此,根据日志,该行返回了一个 NPE:

return this.employeeDAO.listEmployess();

你知道这里有什么问题吗?

提前致谢!

【问题讨论】:

用@Service 注释你的服务 您好,感谢您的快速回复。我在 EmployeeService 类中添加了 @Service 注释,但错误仍然相同。 这些答案可能会有所帮助:***.com/questions/16834333/… 【参考方案1】:

嗨,而不是 setter 方法,在依赖 private EmployeeDAO employeeDAO; 上使用 Autowired 注释

喜欢

 @Autowired    
private EmployeeDAO employeeDAO;

【讨论】:

以上是关于Spring CRUD 应用程序:Servlet [dispatcherServlet] 的 Servlet.service():java.lang.NullPointerException]的主要内容,如果未能解决你的问题,请参考以下文章

具有休眠 CRUD 操作的 Spring 3 注释:@Autowired 未按预期工作

带有 Servlet、JSP 和 MySQL 的 Java 中的 CRUD Web 应用程序,没有 DAO

spring boot 2 - webrestfulCrud实验错误处理机制配置嵌入式Servlet容器

程序员养成之路WEB CRUD的实现流程

CRUD

javaweb实训第四天下午——员工管理系统-JSP&Servlet&JDBC综合练习-CRUD