gpt4 book ai didi

spring-mvc - 更新表格 : Spring mvc + thymeleaf

转载 作者:行者123 更新时间:2023-12-02 11:22:42 25 4
gpt4 key购买 nike

我正在尝试创建一个 thymeleaf 表单来更新支持对象的几个属性:

@RequestMapping(value = "/jobs/{id}", method = RequestMethod.GET)
public ModelAndView update(@PathVariable Integer id ) {
ModelAndView mav = new ModelAndView("updateJob.html");
JobDescription updateJob = jobDescriptionService.findByID(id);
mav.addObject("updateJob", updateJob);
return mav;
}

@RequestMapping(value = "/jobs/{id}", method = RequestMethod.PUT)
public String saveUpdate(@PathVariable Integer id, @ModelAttribute("updateJob") JobDescription updateJob) {
jobDescriptionService.update(updateJob);
return "redirect:/jobs/" + id;
}


<form th:action="@{'/jobs/'+ ${updateJob.id}}" th:object="${updateJob}" th:method="PUT">
<table>
<tr>
<td><label>Description</label></td>
<td><input type="text" th:field="*{description}" /></td>
</tr>
<tr>
<td><label>Deadline</label></td>
<td><input type="text" th:field="*{deadline}" /></td>
</tr>
<tr>
<td></td>
<td><button type="submit">Update</button></td>
</tr>
</table>
</form>

问题是作业对象有几个我不想更新的其他属性(如 id、createdDate 等)。但是,当我单击更新表单的提交按钮时,在 saveUpdate 方法中创建的对象将这些属性设置为 null(除非我将它们设置在表单内的隐藏字段中)。有没有其他办法可以保留它们?

最佳答案

我和你有同样的问题,所以我建立了自己的解决方案

1-您需要在 Controller 上执行两个操作:查看(GET)和操作(POST)

@GetMapping("/user/edit/{userId}")
public ModelAndView editUserView(@PathVariable Long userId) throws NotFoundException {

User user = this.userService.load(userId);

if (user == null) {
throw new NotFoundException("Not found user with ID " + userId);
}

ModelAndView modelAndView = new ModelAndView();

modelAndView.setViewName("user.edit");
modelAndView.addObject("user", user);

return modelAndView;
}

@PostMapping("/user/edit/{userId}")
public ModelAndView editUserAction(HttpServletRequest request, @PathVariable Long userId, @Validated(User.ValidationUpdate.class) User userView,
BindingResult bindingResult) throws Exception {

User user = this.userService.load(userId);

if (user == null) {
throw new NotFoundException("Not found user with ID " + userId);
}

ModelAndView modelAndView = new ModelAndView();
if (bindingResult.hasErrors()) {
modelAndView.setViewName("user.edit");
modelAndView.addObject("user", userView);

return modelAndView;
}

Form.bind(request, userView, user);

this.userService.update(user);

modelAndView.setViewName("redirect:/admin/user");

return modelAndView;
}

2- 一个带有错误显示的 View (非常重要:添加隐藏输入以发送 id 进行验证)
<fieldset th:if="${#fields.hasErrors('${user.*}')}" class="text-warning">
<legend>Some errors appeared !</legend>
<ul>
<li th:each="err : ${#fields.errors('user.*')}" th:text="${err}"></li>
</ul>
</fieldset>

<form action="#" th:action="@{/admin/user/edit/{id}(id=${user.id})}" th:object="${user}" method="post">
<div th:class="${#fields.hasErrors('firstName')} ? 'form-group has-error' : 'form-group'">
<label class="control-label" for="firstName">First Name <span class="required">*</span></label>
<input type="text" th:field="*{firstName}" required="required">
</div>
...
<input type="hidden" th:field="*{id}">
</form>

3- 对于我的示例,我编写了一个 FormUtility 类来合并两个对象:
public static List<String> bind(HttpServletRequest request, Object viewObject, Object daoObject) throws Exception {

if (viewObject.getClass() != daoObject.getClass()) {
throw new Exception("View object and dao object must have same type (class) !");
}

List<String> errorsField = new ArrayList<String>();

// set field value
for (Entry<String, String[]> parameter : request.getParameterMap().entrySet()) {

// build setter/getter method
String setMethodName = "set" + parameter.getKey().substring(0, 1).toUpperCase()
+ parameter.getKey().substring(1);
String getMethodName = "get" + parameter.getKey().substring(0, 1).toUpperCase()
+ parameter.getKey().substring(1);

try {
Method getMethod = daoObject.getClass().getMethod(getMethodName);
Method setMethod = daoObject.getClass().getMethod(setMethodName, getMethod.getReturnType());
setMethod.invoke(daoObject, getMethod.invoke(viewObject));
}
catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException exception) {
errorsField.add(parameter.getKey());
}
}

return errorsField;
}

希望这对你有帮助。

关于spring-mvc - 更新表格 : Spring mvc + thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167675/

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