使用 ajax 将参数传递给控制器

Passing parameter to Controller by using ajax

使用 Spring 引导、MySQL、JPA 和 RESTFUL CRUD API。

我想做的是将参数传递给 Controller,以便参数进入 table。但是空值进入 table 并且我无法弄清楚哪一部分是问题所在。只有我可以确定的是控制器没有收到适当的值。

在下面,我贴出了Entity class(Status.java), Controller(GuideController.java) and html form(guide.html).

Status.java

@Entity
@Table(name="tbl_status")
public class Status {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)

private Integer id;

private String xml_to_json;


public String getXml_to_json() {
    return xml_to_json;
}

public void setXml_to_json(String xml_to_json) {
    this.xml_to_json = xml_to_json;
}

GuideController.java

    @Autowired
private StatusRepository statusRepository;

@GetMapping(path="/insert") // Map ONLY GET Requests
public @ResponseBody String addNewStatus (@RequestParam String xml_to_json
        , @RequestParam String json_to_xml) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    Status s = new Status();
    s.setXml_to_json(xml_to_json);
    //s.setJson_to_xml(json_to_xml);
    statusRepository.save(s);
    return "Saved";
}

@GetMapping(path="/all")
public @ResponseBody Iterable<Status> getAllUsers() {
    // This returns a JSON or XML with the users
    return statusRepository.findAll();
}

guide.html

var xml2json = function(_data){
$.ajax({   
    type: "POST",   
    url: url + "xml2json",   
    data: _data,
    contentType : "application/xml",
    cache: false,
    success : function(data) {   
        $("#output-xml-to-json").html(JSON.stringify(data,null,4));
        $.ajax({
            type:"POST",
            url: url + "insert",
            data: {xml_to_json:"success"},
            contentType: "text"
        })
    },
    error : function(){
        $("#output-xml-to-json").html("xml2json error");
        $.ajax({
            type:"POST",
            url: url + "insert",
            data: {xml_to_json:"error"},
            contentType: "text"
        })
    }
});

}

请求映射为GET:

@GetMapping(path="/insert") // Map ONLY GET Requests
public @ResponseBody String addNewStatus (@RequestParam String xml_to_json
    , @RequestParam String json_to_xml) {...}

并且 AJAX 请求是 POST 和 json 数据。 AJAX 请求应该是 get 并且 xml_to_json 必须在查询字符串中传递。