我已经有一个问题,在这个问题中我没有得到适当的解决。在这个问题上,我会给您更多信息,以给出正确的答案。 Can't bind json string to java string
尝试了该解决方案后, 在模型类中,
public class CreateAds {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// @JsonProperty
private String brand;
// @JsonProperty
private ArrayList<String> models = new ArrayList<>();
//other variable
//all getters and setters
}
在我的控制器中
@PostMapping(value="/create/ads", consumes=MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public String submitForm(@RequestBody CreateAds ads, BindingResult result, Model model) {
if (result.hasErrors()) {
return "test";
}
System.out.println(ads.getBrand()+", "+ads.getModels());
return "successful";
}
在控制器方法中,具有(消耗和生产)或不具有(消耗和生产)的控制器错误
内容类型不是'application / x-www-form-urlencoded; charset = UTF-8' 支持
以我的形式,
<form id="myForm" th:action="@{/create/ads}" th:object="${createAds}" method="post">
<p class="choose__input__single" ><span th:field="*{brand}" id="brands">Brand</span>
</p>
<ul class="dropList odaberiteMarku">
<-- brand -->
</ul>
<p class="choose__input__single"><span th:field="*{model}" id="model">Model</span>
</p>
<ul class="dropList odaberiteModel">
<-- models -->
</ul>
</form>
<script>
$("#myForm").submit(function(e){
var data = {};
data['brand'] = $('[class="odaberiteMarku li label"]').val();
data['models'] = $('[class="odaberiteModel li label"]').val();
$.ajax({
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
type: POST,
url: /create/ads,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(xhr) {
},
success: function(data){
},
return false;
});
});
</script>
获取json api,
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var output = '';
for(var i = 0; i < response.length; i++){
output += `<li class="dropList__item">${response[i].brand}</li>`
}
// SELECT WHERE TO PUT BRAND
var brand = document.querySelector('.odaberiteMarku');
brand.innerHTML = output;
// CHOOSE MODEL BASED ON BRAND
var models = document.querySelectorAll('.odaberiteMarku li');
models.forEach(model=> {
model.addEventListener('click', function(e){
e.preventDefault();
var outputModel = '';
function runOver(){
let auto = model.textContent;
let result = response.find(car => car.brand === auto);
console.log(result.models);
for(let i = 0; i < result.models.length; i++){
outputModel += `<li class="dropList__item">${result.models[i]}</li>`;
}
return outputModel;
}
runOver();
const whereToStore = document.querySelector('.odaberiteModel');
whereToStore.innerHTML = outputModel;
})
})
}
};
xhttp.open("GET", "/json/car-info.json", true);
xhttp.send();
在模型类中,我还有其他字段,而不是json字段。为此,我应该在控制器中使用什么? @RequestBody 或 @ModelAttribute 或两者?
更新:登录时间调试后,我发现选择了品牌和型号,请转到下面的 [span] [p] 标签。现在,我需要将选定的数据发送到模型。
那么我该如何发送数据到模型? 预先感谢。