【发布时间】: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