Не удалось обработать запрос [GET http://localhost:8080]: состояние ответа 404 Spring, RESTfull, thymleaf - PullRequest
0 голосов
/ 19 октября 2018

У меня проблема с Spring, Rest и Thymeleaf, и я застрял там, и у меня не так много подробностей об этой ошибке.

Я хочу, когда я выбираю в форме одиниз опций в теге select (index.html), которые будут перенаправлены в нечто .html, но с новыми значениями (с помощью вызова API), и я просто получаю, что он не может обработать запрос.

Я хочу отправить значение сервису и контроллеру из html-формы:

index.html:

<body>
<!--/*@thymesVar id="cryptos" type="java.util.Map<Integer, jasmin.merusic.domain.Crypto>"*/-->
<!--/*@thymesVar id="crypto" type="jasmin.merusic.domain.Crypto"*/-->
<div class="container-fluid" style="margin-top: 20px">
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="panel panel-primary">

            <div class="panel-heading">
                <h1 class="panel-title">CryptoCurrencies from API</h1>
            </div>
            <div class="panel-body">
                <div class="table-responsive" th:if="${not #maps.isEmpty(cryptos)}">
                    <table class="table table-hover ">
                        <thead class="thead-inverse">
                        <tr>
                            <th>Name</th>
                            <th>
                               **<form th:action="@{/values/}" >
                                <select name="fiatCurrency" onchange="this.form.submit()">
                                <option  selected="selected" value="USD">USD</option>
                                <option  value="EUR">Euro</option>
                                <option  value="CNY">C. Yuan</option>
                                </select>
                               </form>**
                            </th>
                            <th>Change in 24h(%)</th>
                            <th>Rank</th>
                            <th>Symbol</th>
                        </tr>
                        </thead>
                        <tr th:remove="all">
                            <td>Joe</td>
                            <td>Buck</td>
                            <td>Male</td>
                            <td>foo@example.com</td>
                        </tr>
                        <tr th:remove="all">
                            <td>Joe</td>
                            <td>Buck</td>
                            <td>Male</td>
                            <td>foo@example.com</td>
                        </tr>

                        <tr th:each="crypto : ${cryptos.values()}">
                            <td th:text="${crypto.name}">Joe</td>
                                <span th:each="cryp : ${crypto.quotes.values()}">
                                    <td th:text="${cryp.price}">Buck</td>
                                    <td th:text="${cryp.percent_change_24h}">Buck</td>
                                </span>
                            <td th:text="${crypto.rank}">Male</td>
                            <td th:text="${crypto.symbol}">foo@example.com</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
   </div>
</div>
</body>

Класс контроллера выглядит так:

@Controller
public class DataController {

 private  ApiService apiService;

public DataController(ApiService apiService) {
    this.apiService = apiService;
}

@GetMapping({"", "/", "/index","/cryptos"})
public String index(Model model){

    model.addAttribute("cryptos",apiService.getCrypto(100));

    return "index";
}

@PostMapping(value = "/values/{fiatCurrency}")
public String choseCurrency(Model model,@PathVariable String fiatCurrency){

    model.addAttribute("cryp",apiService.getInDifferentValues(fiatCurrency));

     //returns to the something.html
    return "something";
}
}

И реализация сервиса выглядит так:

@Service
public class ApiServiceImpl implements ApiService{

private  RestTemplate restTemplate;

@Autowired
public ApiServiceImpl(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}

@Override
public Map<Integer,Crypto> getCrypto(Integer limit) {

    CryptoData cryptoData = restTemplate.getForObject("https://api.coinmarketcap.com/v2/ticker/?convert=BTC&limit=" + limit , CryptoData.class);


    return cryptoData.getData();
}

@Override
public Map<Integer, Crypto> getInDifferentValues(String fiatCurrency) {

    CryptoData cryptoData = restTemplate.
            getForObject("https://api.coinmarketcap.com/v2/ticker/?convert=" + fiatCurrency + "&limit=100", CryptoData.class);

    return cryptoData.getData();
}
}

Я новичок в этом, и я столкнулся со следующей ошибкой:

2018-10-19 20:10:40.147  WARN 15768 --- [ctor-http-nio-4] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [GET http://localhost:8080/values/?fiatCurrency=EUR]: Response status 404

Ответы [ 2 ]

0 голосов
/ 19 октября 2018

Попробуйте изменить эту строку

**<form th:action="@{/values/}" >

на

**<form th:action="@{/values/} + ${fiatCurrency}" method="post" >

Это изменит запрос на "post" с "get" (у вас есть "get" сейчас в вашей форме) и отправит информацию в виде переменной пути (как определено в вашем методе контроллера), а не в качестве параметра запроса (как сейчас).

0 голосов
/ 19 октября 2018

Согласно вашей трассировке стека ошибок,

2018-10-19 20: 10: 40.147 WARN 15768 --- [ctor-http-nio-4] .awreDefaultErrorWebExceptionHandler: не удалось обработатьзапрос [GET http://localhost:8080/values/?fiatCurrency=EUR]: Статус ответа 404

Вы не определили отображение GET для /values.Вы определили его только для операции POST, добавьте его, и оно должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...