java - 保存 ModelAttribute 时出现空指针异常 [Spring MVC]

标签 java spring mongodb spring-mvc modelattribute

在基于 Spring MVC 的项目上工作时,我在尝试保存评论(Bean)时收到以下代码。我能够成功地将数据输入 Controller ,但由于某种原因在保存时出现 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>

-- Controller --

      @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

}

我收到以下错误消息,正如您所看到的数据(模型属性已在 Controller 中成功捕获,但由于 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

最佳答案

我能够解决这个问题。这是因为我没有在reviewsMongoRepository上应用@Autowired,所以它没有与review bean链接。我纠正了这个问题,现在它可以工作了。谢谢您

关于java - 保存 ModelAttribute 时出现空指针异常 [Spring MVC],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503756/

相关文章:

node.js - Sails.js 升级到 v1 反向区分大小写的查询

java - 为什么在调试程序时添加元素时列表没有变化?

java - Jenkins 可以配置为独立于其他作业运行一组作业吗?

spring - 密封类作为一个实体

java - DDD Java with Spring - Repository 返回 Mono/Flux

java - org.springframework.batch.item.ItemStreamException : File already exists: [SpringBatch-Partitioner-Example\csv\outputs\users.processed21-30.csv]

java - 测试 ClassNotFound 异常

java - HQL - 通过电子邮件或带点 ('.' 的字符串查询始终返回空集

java - Spring 状态机转换

java - Spring 3.2.8 应用程序中出现 HTTP 404 Not Found 错误