gpt4 book ai didi

SpringMVC PUT request to edit data but instead, got a new one(SpringMVC发出了编辑数据的请求,但得到了一个新的请求)

转载 作者:bug小助手 更新时间:2023-10-28 10:56:45 26 4
gpt4 key购买 nike



I'm practicing Spring/Thymeleaf and facing an issue
I create a a PUT request to edit but instead it act as POST by create a new data

我正在练习Spring/Thymeleaf,面对一个问题,我创建了一个要编辑的PUT请求,但它通过创建一个新数据来充当POST


Here are my codes
Controller

以下是我的代码控制器


// imports



@Autowired
private UniversityService universityService;

// More codes


@PutMapping("/universities/{id}/edit")
public String editUniversity(
@Valid @ModelAttribute("thisUniversity") University updatedUniversity,
BindingResult result,
@PathVariable Long id) {
if(result.hasErrors()) {
return "editUniversity";
}
universityService.updateUniversity(updatedUniversity);
return "redirect:/";
}


Service

服务


// imports

@Service
public class UniversityService {

@Autowired
private UniversityRepo universityRepo;

// Add a university
public University createUniversity (University newUniversity) {
return universityRepo.save(newUniversity);
}


// More codes


public University updateUniversity(University updatedUniversity) {
return universityRepo.save(updatedUniversity);
}

}

HTML

超文本标记语言


<!DOCTYPE html>
<1-- head -->
<form th:taction="@{'/universities/'+${thisUniversity.universityId}+'/edit'}" th:object="${thisUniversity}" th:method="POST">
<!-- The below tag is required for PUT/DELETE request -->
<input type="hidden" name="_method" value="PUT">

// HTML elements

<input type="submit" value="Save University">
</form>

I also have spring.mvc.hiddenmethod.filter.enabled=true in application.properties file

我在应用程序的属性文件中也有spring.mvc.iddenmethod.filter.Enabled=True


I have try th:method="PUT" in form tag or not including <input type="hidden" name="_method" value="PUT">
But the results are still the same

我在表单标签中尝试了th:method=“PUT”或不包含,但结果仍然相同


更多回答

Stop using entities in your api. Learn about 3tier architecture

停止在API中使用实体。了解3TIER架构

Has your updatedUniversity entity a proper id set?

您的更新版大学实体是否设置了正确的ID?

优秀答案推荐

You're taking the id as a path variable but not giving it to the updated object, which is why it gets saved to a new object instead of editing the existing one.

您将id作为路径变量,但没有将其提供给更新后的对象,这就是将其保存到新对象而不是编辑现有对象的原因。


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com