【问题标题】:Spring Controller throws NullPointerException when Pass Integer Data With Ajax/PostSpring Controller 在使用 Ajax/Post 传递整数数据时抛出 NullPointerException
【发布时间】:2019-03-24 13:30:03
【问题描述】:

我正在尝试以 html 形式传递一组数据;

<form class="form-inline" id="createjobform" method="POST" th:action="@{/createJob}">
...
<div class="form-group">
    <input type="text" class="form-control" id="nopth"
    placeholder="Number Of People To Hire" name="nopth" />
</div>
<div class="form-group">
    <input type="text" readonly="readonly" class="form-control"
    id="listid" placeholder="ID" name="listid"
    title="ID of the list which associated" 
    th:value="${findOneList.id}"/>
</div>

这里的listid,来自另一个表(manytoone-onetomany),我想用这个listid添加新记录。当我在 phpmyadmin 上执行此操作时,它正在工作。但我想用 ajax 发布请求或不用 ajax 来做,不管实际上。两种方法都试过了,还是一样的错误。

这是我的控制器;

@RequestMapping(value = "/createJob", method = RequestMethod.POST)
public @ResponseBody void createJob(@RequestBody Jobs jobs,
        @RequestParam(value = "title", required = false) String title,
        @RequestParam(value = "description", required = false) String description,
        @RequestParam(value = "nopth", required = false) Integer nopth,
        @RequestParam(value = "lastDate", required = false) Date lastDate,
        @RequestParam(value = "listid", required = false) Long listid,
        HttpServletResponse hsr) throws IOException {

    // if I do String nopth above and then
    //jobs.setNopth(Integer.valueOf(nopth));
    // error is NumberFormatException (cannot cast string to int)

    jobs.setLastDate(lastDate);
    jobs.setTitle(title);
    jobs.setDescription(description);
    jobs.setNopth(nopth);
    Lists listttt = listsService.findOne(listid);
    jobs.setLists(listttt);

    jobsService.save(jobs);
    mavHomepage.addObject("findOneList", listsService.findOne(jobs.getId()));
    mavHomepage.addObject("mod", "VIEW_ONELIST");
    hsr.sendRedirect("/oneList?id=" + listid);
}

所以错误是;

error: "Internal Server Error"
exception: "java.lang.NullPointerException"
message: "No message available"
path: "/createJob"
status: 500

在线jobs.setNopth(nopth);

还有错误;

error: "Internal Server Error"
exception: "org.springframework.dao.InvalidDataAccessApiUsageException"
message: "The given id must not be null!; nested exception is 
java.lang.IllegalArgumentException: The given id must not be null!"
path: "/createJob"
status: 500

在行列表 listttt = listsService.findOne(listid);

这不适用于 ajax/post。当我这样做时;

public @ResponseBody void createJob(@RequestBody Jobs jobs,
    @RequestParam(value="listid, required="false") listid,
    HttpServletResponse hsr){

        Lists listttt = listsService.findOne(listid);
        jobs.setLists(listttt);
         ...
}

和ajax;

var formData = {
    title : $("#title").val(),
    description : $("#description").val(),
    nopth : $("#nopth").val(),
    lastDate : $("#lastDate").val(),
    listid : $("#listid").val(),
}
...
$.ajax({
        type : "POST",
        contentType : "application/json",
        url : "/createJob",
        data : JSON.stringify(formData),
....

同样的错误(给定的id不能为空!)

那么我必须如何从整数/长值形式传递数据?使用 AJAX 会更好。并且那个 listid 是 FOREIGN KEY。

模型类;

@Entity(name = "jobs")
public class Jobs {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "Title")
private String title;

@Column(name = "Description")
private String description;

@Column(name = "Number_Of_People_To_Hire")
private Integer nopth;

@Column(name = "Last_Application_Date")
private Date lastDate;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="listid")
private Lists lists;

...

@Entity(name = "lists")
public class Lists implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;

@Column(name = "List_Name")
public String listname;

@OneToMany(mappedBy = "lists", cascade = CascadeType.ALL)
private List<Jobs> jobs;

我尝试将 nopth 的类型更改为 String、Integer 等并输入 type="text or number" 没有变化。

【问题讨论】:

    标签: ajax spring-boot thymeleaf


    【解决方案1】:
    • @RequestBody这个注解表示方法参数应该绑定到web请求的body上
    • 所以你必须像这样修复你的控制器:

      @RequestMapping(value = "/createJob", method = RequestMethod.POST)
      @ResponseBody
      public void createJob(
          @RequestBody Jobs jobs,
          @RequestParam("listid") Long listid
          HttpServletResponse hsr) throws IOException {
      
         Lists listttt = listsService.findOne(listid);
         jobs.setLists(listttt);
      
         jobsService.save(jobs);
      
         ...
      
      }
      
    • 您的 jquery 请求:

      var formData = {
          title : $("#title").val(),
          description : $("#description").val(),
          nopth : $("#nopth").val(),
          lastDate : $("#lastDate").val()
      }
      
      var listid : $("#listid").val(),
      
      var settings = {
        "url": "http://localhost:8080/createJob?listid="+listid,
        "method": "POST",
        "data": JSON.stringify(formData)
        "headers": {
          "Content-Type": "application/json"
        }
       }
      
       $.ajax(settings).done(function (response) {
         console.log(response);
       });
      

    【讨论】:

    • mavHomepage.addObject("findOneList", listsService.findOne(jobs.getId())); 在这一行您收到错误消息,因为您当前的 jobs 对象没有 id 的初始值,所以当您保存 jobs 对象 试试这个:Jobs newJobs = jobsService.save(jobs); 此时你的 newJobs 对象 有一个 id ,所以你可以这样做:mavHomepage.addObject("findOneList", listsService.findOne(newJobs.getId()));
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2021-12-25
    • 2017-12-26
    • 2019-09-15
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多