Как отправить данные со страницы thymeleaf HTML на контроллер пружинной загрузки MVC? - PullRequest
0 голосов
/ 10 января 2020

Я новичок в тимилфиле и весне, и я пытаюсь отправить простые входные данные со страницы индекса на контроллер, поэтому я создал объект Exchange, показанный ниже, где он будет содержать поля входных данных для обработки. Проблема в том, что я получаю сообщение об ошибке, показанное на картинке

, вот мой объект Exchange

package myprivate.work.MyCurrencyConverter.model;
public class Exchange
{
    private String fromcurrency;
    private String tocurrency;
    private double amount;
    public Exchange(){
       super();
    }
    public Exchange(String fromcurrency, String tocurrency, double amount) {
        super();
        this.fromcurrency = fromcurrency;
        this.tocurrency = tocurrency;
        this.amount = amount;
    }
    public String getFromcurrency() {
        return fromcurrency;
    }
    public void setFromcurrency(String fromcurrency) {
        this.fromcurrency = fromcurrency;
    }
    public String getTocurrency() {
        return tocurrency;
    }
    public void setTocurrency(String tocurrency) {
        this.tocurrency = tocurrency;
    }
    public double getAmount() {
        return amount;
    }
    public void setAmount(double amount) {
        this.amount = amount;
    }
}

, и это форма, которую я имею в индексе

<form th:action="@{/newexchange}" th:object="${exchange}" method='POST'>
    <p>Select From Currency:</p>
    <p>
        <select th:field="*{fromcurrency}"> <!-- this is line 12 -->
            <option th:value="sek">SEK</option>
            <option th:value="eur">EUR</option>
            <option th:value="usd">USD</option>
            <option th:value="jpy">JPY</option>
        </select>
    </p>
    <p>Select To Currency:</p>
    <p>
        <select th:field="*{tocurrency}">
            <option th:value="sek">SEK</option>
            <option th:value="eur">EUR</option>
            <option th:value="usd">USD</option>
            <option th:value="jpy">JPY</option>
        </select>
    </p>
    <p class="form"><label>Insert New Rate:</label><input type="number" th:field="*{amount}"/>
    </p>
    <p><input name="Convert" type="submit" value="submit"/></p>
</form>

и в моем контроллере

@RequestMapping(method = RequestMethod.POST , value = "/newexchange")
public String toExchange(Exchange exchange, BindingResult result)
{
    return "..ok..";
}

вот error and

Ответы [ 3 ]

0 голосов
/ 10 января 2020

Я думаю, вы должны использовать @ModelAttribute в своем контроллере для захвата объекта Exchange примерно так:

Controller:

    @RequestMapping(value = "/showForm", method=RequestMethod.GET)
public String showForm(Model model) {
  Foo foo = new Foo();
  foo.setBar("bar");

  model.addAttribute("foo", foo);
  ...
}

@RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="foo") Foo foo) {
  ...
}


html :

<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
  <input type="text" th:field="*{bar}" />
  <input type="submit" />
</form>

Model Data :

public class Foo {
  private String bar;

  public String getBar() {
    return bar;
  }

  public void setBar(String bar) {
    this.bar = bar;
  }
}
0 голосов
/ 10 января 2020

Используйте @ModelAttribute для получения данных со страницы индекса в Controller-

 @RequestMapping(method = RequestMethod.POST , value = "/newexchange")
    public String toExchange(@ModelAttribute Exchange exchange, BindingResult result)
    {
       logger.logInfo("Exchange Amount->>"+exchange.getAmount());
      return "..ok..";
    }
0 голосов
/ 10 января 2020

Вы должны указать Thymeleaf, на какой объект вы ссылаетесь. Вам нужно будет передать на страницу ModelAttribute, чтобы Thymeleaf знал, с каким объектом связать свойства.

При использовании синтаксиса звездочки *{...} вычисляется выражение для выбранного объекта на th:object.

Примерно так:

// this method need to show your exchange page
@GetMapping("/exchange")
public String handleGetRegisterRequest(
        @ModelAttribute Exchange exchange) { // your object (Thymeleaf will receive this to bind with the parameters you pass)
    return "exchange"; // the name of your page which contains the exchange informations
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...