使用Ajax / Post传递整数数据时,Spring Controller会引发NullPointerException

时间:2019-03-24 13:30:04

标签: ajax spring-boot thymeleaf

我正在尝试以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不能为null!)

那我该如何从整数或长值形式的数据中传递数据?使用AJAX会更好。并且listid是外键。

模型类;

@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或number”不变。

1 个答案:

答案 0 :(得分:0)

  • @RequestBody此注释指示方法参数应绑定到Web请求的正文
  • 所以您必须像这样修复控制器:

    @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);
     });