Thymeleaf模板图片src属性格式错误,需符合RFC 7230与RFC 3986规范
问题解决:Thymeleaf图片URL动态生成失败及非法字符错误
问题根源
- 未使用Thymeleaf专属属性:你使用了普通的
src属性而非th:src,导致Thymeleaf无法解析@{}语法,浏览器直接将未处理的表达式作为URL发送给服务器,触发非法字符错误。 - URL变量语法错误:在
@{}内部,不能使用*{profileImageId}这种相对对象的字段表达式,需要用${}直接引用对象属性来完成变量替换。
修正后的代码
将图片标签替换为以下代码:
<form action="#" th:object="${userDto}" method="post"> ... <img alt="" th:src="@{/ProfileImageServlet?imageId=${userDto.profileImageId}}" width="100" style="border-radius: 50%;" > </form>
或者,利用th:object的上下文,使用${#object}简化引用:
<img alt="" th:src="@{/ProfileImageServlet?imageId=${#object.profileImageId}}" width="100" style="border-radius: 50%;" >
补充说明
th:src是Thymeleaf的专属属性,会在模板渲染时解析其中的表达式,生成合法的URL。@{}内部的${userDto.profileImageId}会被替换为实际的profileImageId值,避免非法字符出现在请求URL中。
内容的提问来源于stack exchange,提问作者Singam
相关产品推荐
相关产品推荐

