使用PathVariable时CSS加载失败及Thymeleaf表单回显问题
问题1:Thymeleaf表单字段回显值不生效
你同时使用th:field和th:value设置输入框值,但**th:field会自动覆盖th:value**——因为th:field是用来和th:object绑定的,它会优先从${createOffenceForm}里取对应字段的值,而非你设置的${currentOffence}。
解决方法有两种:
- 后端填充绑定对象:把
currentOffence的字段值提前赋值给createOffenceForm,比如在Controller中:
前端仅保留createOffenceForm.setName(currentOffence.getName()); createOffenceForm.setPenaltyPoints(currentOffence.getPenaltyPoints()); createOffenceForm.setAmountOfFine(currentOffence.getAmountOfFine()); // 将createOffenceForm放入Model传递给前端th:field即可:<form th:action="@{/offences/edit}" method="post" th:object="${createOffenceForm}"> <input th:field="*{name}"/> <input th:field="*{penaltyPoints}"/> <input th:field="*{amountOfFine}"/> <button type="submit">UPDATE</button> </form> - 弃用
th:field,手动绑定参数:若不想修改后端,直接移除th:field,用普通name属性配合th:value,确保name与后端接收参数名一致:<form th:action="@{/offences/edit}" method="post"> <input name="name" th:value="${currentOffence.name}"/> <input name="penaltyPoints" th:value="${currentOffence.penaltyPoints}"/> <input name="amountOfFine" th:value="${currentOffence.amountOfFine}"/> <button type="submit">UPDATE</button> </form>
问题2:带PathVariable跳转后CSS样式失效
这是因为你用了相对路径引用CSS(比如css/style.css),当跳转到/offences/edit/1这类多级路径时,浏览器会将当前路径识别为/offences/edit/,进而请求/offences/edit/css/style.css,导致找不到样式文件。
解决方法是用Thymeleaf的绝对路径语法@{...}引用静态资源:
将原CSS引用:
<link rel="stylesheet" href="css/style.css">
修改为:
<link rel="stylesheet" th:href="@{/css/style.css}">
这样无论当前页面处于什么路径,都会从项目根目录加载CSS,样式就不会失效了。
内容的提问来源于stack exchange,提问作者Lulex97
相关产品推荐
相关产品推荐

