【问题标题】:HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException after refactoring Service classHTTP 状态 500 - 请求处理失败;重构Service类后嵌套异常为java.lang.NullPointerException
【发布时间】:2015-09-15 09:51:04
【问题描述】:

早期我有两个服务 PersonService 和 ActionService 但现在我认为最好只有一个服务。我构建了它,但是当我运行我的应用程序时,我得到了 NullPointerException。有人可以帮忙吗?

下面的控制器类

@Controller
@RequestMapping("/main")
public class MainController {

private static Logger LOGGER = Logger.getLogger("Controller");

@Autowired
private UserService userService;


@RequestMapping(value = "/users" , method = RequestMethod.GET)
public String getUsers(Model model) {

    LOGGER.debug("Receive request for show all users");
    List<User> users = userService.getAll();
    model.addAttribute("users", users);
    return "userspage";

}

@RequestMapping(value = "/users/add", method = RequestMethod.GET)
public String getAdd() {

    LOGGER.debug("Receive request to show add page");
    return "addpage";

}

@RequestMapping(value = "/users/add", method = RequestMethod.POST)
public String add(@ModelAttribute("userAttribute") User user) {

    LOGGER.debug("Recieve request to add a new user");
    userService.add(user);
    return "addedpage";

}

@RequestMapping(value = "/users/delete", method = RequestMethod.GET)
public String delete(@RequestParam(value = "id", required = true)Integer 
id, Model model) {

    LOGGER.debug("Recieve request for deleting user");
    userService.delete(id);
    model.addAttribute("id", id);
    return "deletedpage";

}

@RequestMapping(value = "/users/edit", method = RequestMethod.GET)
public String getEdit(@RequestParam(value = "id", required = true)Integer 
id, Model model) {

    LOGGER.debug("Recieve request to show editpage");
    model.addAttribute("userAttribute", userService.get(id));
    return "editpage";

}

@RequestMapping(value = "/users/edit", method = RequestMethod.POST)
public String saveEdit(@ModelAttribute("userAttribute") User user,
                       @RequestParam(value = "id", required = 
true)Integer id, Model model) {

    LOGGER.debug("Received request to update person");
    user.setId(id);
    userService.edit(user);
    model.addAttribute("id", id);
    return "editedpage";

}

@RequestMapping(value = "/users/actions", method = RequestMethod.GET)
public String getActionsOfUser(@RequestParam(value = "id", required = 
true)Integer id, Model model, User user){

    LOGGER.debug("Recieve request to show user Action");
    model.addAttribute("userId", userService.get(id));
    model.addAttribute("userAction", userService.getListOfActions(user));
    return "userActionsPage";

}
}

下面的服务类

@Service
@Transactional
public class UserServiceImpl implements UserService {

private static Logger LOGGER = Logger.getLogger("UserService");

@Autowired
private SessionFactory sessionFactory;

public List<User> getAll() {

    LOGGER.debug("Retrieving all users");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User ");
    return query.list();

}

public List<Actions> getListOfActions(User user) {

    LOGGER.debug("Retriving all user actions");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from Actions where  user = " +   
user.getId());
    return query.list();
}


public User get(Integer id) {

    Session session = sessionFactory.getCurrentSession();
    User user = (User) session.get(User.class, id);
    return user;

}

public void add(User user) {

    LOGGER.debug("Adding new user");
    Session session = sessionFactory.getCurrentSession();
    Actions actions = new Actions();
    actions.setActionType(ActionType.ADDING_NEW_USER);
    actions.setDate(new Date());
    actions.setUser(user);
    user.getActions().add(actions);
    session.save(user);
    session.save(actions);

}

public void delete(Integer id) {

    LOGGER.debug("Deleting existing user");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User where id = " + id);
    User user = (User) query.uniqueResult();
    List<Actions> actions = user.getActions();
    session.delete(user);
    for(Actions actionses: actions ){
        session.delete(actionses);
    }

}

public void edit(User user) {

    LOGGER.debug("Editing existing user");
    Session session = sessionFactory.getCurrentSession();
    User existingUser = (User) session.get(User.class, user.getId());
    existingUser.setLogin(user.getLogin());
    existingUser.setPassword(user.getPassword());
    existingUser.setReal_name(user.getReal_name());
    Actions actions = new Actions();
    actions.setActionType(ActionType.EDITING_EXISTING_USER);
    actions.setDate(new Date());
    actions.setUser(user);
    user.getActions().add(actions);

    session.save(existingUser);

}
}

应用程序上下文

<?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: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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be  
auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct 
base-package-->
<context:component-scan base-package="com.oleg.project" />

<!-- Configures the annotation-driven Spring MVC Controller programming  
model.-->
<mvc:annotation-driven />

<!-- Load Hibernate related configuration -->
<import resource="hibernate-context.xml" />

</beans>

这里是堆栈跟踪

SEVERE: Servlet.service() for servlet [spring] in context with path []  
threw exception [Request processing failed; nested exception is  
java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.oleg.project.services.UserServiceImpl.add(UserServiceImpl.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy24.add(Unknown Source)
at com.oleg.project.controller.MainController.add(MainController.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

  • 疯狂猜测 user.getActions() 返回 null... 实际上猜测是第 61 行是 user.getActions().add(actions);。
  • UserServiceImpl.java 和第 61 行是什么?因为它是这么说的。
  • 但是我该如何解决这个问题呢?我认为为 addAction 添加单个方法,获取现有用户并为他添加操作将是愚蠢的解决...
  • 你不应该允许像getActions().add() 这样的东西,因为你现在暴露了内部状态并允许外部修改。这是错误的,尤其是如果你也有一个setActions,这在使用托管对象和托管集合时尤其危险!

标签: java spring hibernate model-view-controller


【解决方案1】:

看到user.getActions().add(actions); 这样的代码时,我总是感到难过。您现在正在公开内部状态并让它被外部世界修改。可能还有一个setActions() 方法可以做这样的事情

public void setActions(Collection actions) {
    this.actions=actions;
}

这会完全搞砸您的托管对象和集合并混淆休眠状态。你不应该这样做。而是在您的用户上添加 addAction 和 removeAction 方法,并始终使用空集合初始化 actions 集合。 (我在这里使用的示例假设您使用的是Set。

public class User {

    @OneToMany(mapedBy="user", cascade=ALL, orphanRemoval=true)
    private final Set<Actions> actions = new HashSet<Actions>();

     // Getter only, no setter!
     public Set<Actions> getActions() {
         return Collections.unmodifiableSet(this.actions);
     }

     public void addActions(Actions actions) {
          this.actions.add(actions);
          actions.setUser(this); // Only if bi-directional relation
     }

     public void removeActions(Actions actions) {
          this.actions.remove(actions);
          actions.setUser(null);
     }
}

还要注意用户上的@OneToMany 注释。有了这个,您只需要保存或删除 User 而不是单个 Actions 实体。这基本上现在已正确映射和管理。

您的add 方法可能看起来像这样。

public void add(User user) {

    LOGGER.debug("Adding new user");
    Session session = sessionFactory.getCurrentSession();
    Actions actions = new Actions();
    actions.setActionType(ActionType.ADDING_NEW_USER);
    actions.setDate(new Date());
    user.addActions(actions);
    session.save(user);
}

而且删除更简单。

public void delete(Integer id) {

    LOGGER.debug("Deleting existing user");
    Session session = sessionFactory.getCurrentSession();
    User user = (User) session.get(User.class, id);
    session.delete(user);
}

您当然需要相应地修改其他方法。

您拥有的代码是(恕我直言)不正确的集合管理和实体映射的标志。

【讨论】:

  • 谢谢,精彩的回答。你真的帮了我
  • 但现在我的表在断开连接后不会掉线
  • 为什么你的表会被删除?
  • 因为我在“数据源”bean 中有销毁方法
  • 那么...你的表会被删除吗...销毁数据源与删除表不一样...这些是不同的事情,甚至没有轻微的相关性。
【解决方案2】:

这可能不是你的情况,但可能对另一个面临同样挑战的人有用。

我忘记在我的 pom.xml 中添加 mysql 依赖项。如果这是您的情况,请将其添加到您的 pom 中

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.31</version>
</dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多