保存ModelAttribute [Spring MVC]时获取空指针异常

时间:2016-05-28 21:09:18

标签: java spring mongodb spring-mvc modelattribute

在基于Spring MVC的项目上工作时,我在尝试保存评论(Bean)时收到以下代码。我能够成功地将数据导入控制器,但由于某种原因在保存时获得了NULL指针异常。

这是代码

- JSP--

      <div class="col-md-12">
                            <div class="p-b">
                                <cf:form action="${pageContext.request.contextPath}/reviews/add" id="reviewAction" modelAttribute="review" method="post" accept-charset="utf-8">
                                    <div style="display:none">
                                        <cf:input path="tutorId" type="hidden" name="tutorId" id="tutorId" value="" />
                                        <cf:input path="studentId" type="hidden" name="studentId" id="studentId" value="${sessionScope.user.userId}" />
                                    </div>
                                    <label>Your Comment / Review</label>
                                    <cf:textarea path="reviewMessage" name="reviewMessage" required="required"/>
                                    <p class="text-right"><input type="submit" class="btn btn-default btn-sm" name="submit" value="Post"> </p>
                                </cf:form>
                            </div>
                        </div>



     <cf:hidden path="userId" id="userId"/>



     <script type="text/javascript">
    $(document).ready(function () {
        console.log("Calling getTutorId()");

        getTutorId();

    });

    function getTutorId()
    {
        $('#tutorId').attr('value',$('#userId').val());

    }
    </script>

- 控制器 -

      @RequestMapping (value = "/add" , method = RequestMethod.POST)
       public String addReview(@Valid @ModelAttribute Review review , BindingResult bindingResult, Model model) {

    try {
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getAllErrors().iterator().next().toString());
            return "FindTutor";
        }

        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date date = new Date();
        String newDate = dateFormat.format(date); //06/08/2016 15:59:48

        review.setDate(newDate);
        review.setReviewStatus("Disapproved");

        //Just for testing purposes
        System.out.println(review.getStudentId());
        System.out.println(review.getTutorId());
        System.out.println(review.getDate());
        System.out.println(review.getReviewMessage());
        System.out.println(review.getReviewStatus());
        //Just for testing purposes

            reviewBL.saveReview(review);

        List<Subject> subjectList = subjectBL.getAllSubjects();
        List<User> userList = manageUserBL.getAllUsers();

        model.addAttribute("subjectList", subjectList);
        model.addAttribute("userList", userList);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "FindTutor";
}

- 业务逻辑类 -

    @Service
  public class ReviewBL {

private ReviewsMongoRepository reviewsMongoRepository;

public void saveReview(Review review)
{
    if (StringUtils.isEmpty(review.getId())) {
        review.setId(null);
    }

    reviewsMongoRepository.save(review);
}


}

- Bean类 -

  @Document (collection = "reviews")
  public class Review {

@Id
private String Id;

private String tutorId;

private String studentId;

private String date;

private String reviewMessage;

private String reviewStatus;

// plus constructors also all of the getters and setters

}

我收到以下错误消息,并且您可以看到数据(模型属性已成功捕获在控制器中但由于NULL指针异常错误未被保存在数据库中,我似乎无法找出原因

       2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO           e.b.fyp.stp.web.filter.SessionFilter - Filtering: /reviews/add
 java.lang.NullPointerException
at edu.bnu.fyp.stp.bl.ReviewBL.saveReview(ReviewBL.java:23)
at  edu.bnu.fyp.stp.web.controller.student.ReviewController.addReview(ReviewControll er.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:606)
   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:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
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:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
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 edu.bnu.fyp.stp.web.filter.SessionFilter.doFilter(SessionFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
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.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

  574939f19fcf9da523b63f8b // ID 1 (String)
  57493a3e9fcf9da523b63f8c // ID 2 (String)
  28/05/2016 13:16:59 //Date (String)
  Great Tutor // Message (String)
  Disapproved //Status (String)

  2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO       e.b.fyp.stp.web.filter.SessionFilter - Filtering: /WEB-INF/jsp/FindTutor.jsp

2 个答案:

答案 0 :(得分:1)

我能够解决这个问题。这是因为我没有将@Autowired应用于reviewsMongoRepository,因此它没有与review bean链接。我纠正了这一点,现在它正在发挥作用。谢谢

答案 1 :(得分:0)

ReviewBL.saveReview 内,您正在调用 reviewsMongoRepository.save(review) 但我可以看到你没有初始化 reviewsMongoRepository ,这只是一个引用&#34; nothhing的引用类型。&#34;它可能是您的空指针异常的原因