Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

javascript - 手动构建模型属性以提交给弹簧控制器(Manually build a model attribute to submit to a spring controller)

I need submit a object to this controller:(我需要向该控制器提交一个对象:)

  @RequestMapping(value = "/insert_pedido", method=RequestMethod.POST)
  @ResponseBody
  public String insert_pedido(@RequestParam("cliente") Integer cliente_id, @ModelAttribute("pedido") Pedido pedido) throws JsonProcessingException {
...
  }

through a javascript function like that:(通过像这样的javascript函数:)

function insert_pedido(e) {
  var cliente = e.dataset.cliente;
  var pedido = ?
  var url = e.dataset.url;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url_pedido, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
...
    }
  };
  formData = new FormData();
  formData.append("cliente", cliente);
  formData.append("pedido", pedido);
  xhr.send(formData);
}

I need build the data the controller will be reading by @ModelAttribute("pedido") Pedido pedido in the variable pedido .(我需要构建控制器将通过变量pedido中的@ModelAttribute("pedido") Pedido pedido读取的数据。)

Is this possible?(这可能吗?) If so, how I could do that?(如果是这样,我该怎么做?)

the fields need to be added to this object are:(需要添加到该对象的字段是:)

        <div class="form" id="inner-form">
          <div class="form-group">
            <label for="transactionId">transactionId</label>
            <input type="text" name="transactionId" class="form-control" id="transactionId">
          </div>

          <div class="form-group">
            <label for="metodoPagamento">metodoPagamento</label>
            <input type="text" name="metodoPagamento" class="form-control" id="metodoPagamento">
          </div>

          <div class="form-group">
            <label for="dataCompra">dataCompra</label>
            <input type="date" name="dataCompra" class="form-control" id="dataCompra">
          </div>

          <input th:if="${command}" type="hidden" name="cliente" th:value="${command.id}">

          <div class="form-group">
            <label for="produtos">produtos</label>
            <select multiple="multiple" class="form-control" id="produtos" name="produtos">
              <option th:each="option : ${produtos}" th:value="${option.id}" th:text="${option.nome}"></option>
            </select>
          </div>
        </div>

UPDATE(更新)

I try this:(我尝试这样:)

  var pedido = new FormData();
  pedido.append('transactionId', document.getElementById('transactionId').value);
  pedido.append('metodoPagamento', document.getElementById('metodoPagamento').value);
  pedido.append('dataCompra', document.getElementById('dataCompra').value);
  pedido.append('produtos', document.getElementById('produtos').value);

which I persistig an entity pedido on the database, but with all the fields empty.(我在数据库上保留了一个实体pedido ,但所有字段均为空。)

Even in the javascript code, if I add this:(即使在javascript代码中,如果我添加以下代码:)

  console.log(' transactionId: '+document.getElementById('transactionId').value);
  console.log(' metodoPagamento: '+document.getElementById('metodoPagamento').value);
  console.log(' dataCompra: '+document.getElementById('dataCompra').value);
  console.log(' cliente: '+document.getElementById('cliente').value);
  console.log(' produtos: '+document.getElementById('produtos').value);

only the fields dataCompra and cliente are getting the correct values.(只有字段dataCompracliente获得正确的值。)

The others are getting null value.(其他正在获得null值。) All with the html above.(全部带有上面的html。)   ask by Kleber Mota translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's been a while since I worked with Spring, but something like this should work:(自从我与Spring合作以来已经有一段时间了,但是这样的事情应该可以工作:)

@PostMapping(
  value = "/insert_pedido", consumes = "application/json", produces = "application/json")
public String insert_pedido(@RequestBody Pedido pedido) {
    return pedidoService.insert(pedido);
}

For the client js, you will sadly need to get the json model from the DOM manually (since you're not using a form or model defined in JS that you apply to a template ==> although this is what I'd suggest you to do anyway).(对于客户端js,可悲的是,您将需要手动从DOM中获取json模型(因为您未使用JS中定义的应用于模板==>的表单或模型,尽管这是我建议的方式)无论如何)。)

Then you just perform the ajax call(然后,您只需执行ajax调用)

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/insert_pedido");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({ ... })); // => Your json object here 

Also check the properties on your Java objects (getters and setters) or use a plugin like lombok.(还要检查Java对象(getter和setter)上的属性,或使用lombok之类的插件。)


Although it's sort of ugly, your last edit does indeed the manual dom crawling.(尽管有点丑陋,但您的上一次编辑确实确实进行了手动dom爬网。) Check that all your values are properly retrieved and sent over the network (eg Chrome network tab).(检查所有值均已正确检索并通过网络发送(例如Chrome网络标签)。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...