我已经将thymeleaf和spring test添加到我的spring boot项目中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
然后我创建了一个简单的服务来执行渲染:
package com.myorg.myproject.service
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.stereotype.Service
import org.springframework.web.servlet.ViewResolver
import java.util.*
@Service
class HtmlRenderer {
@Autowired
private lateinit var viewResolver: ViewResolver
fun render(): String {
val resolvedView = viewResolver.resolveViewName("activity", Locale.US)
?: throw Exception("Unable to find view.")
val mockRequest = MockHttpServletRequest()
mockRequest.contentType = "text/html"
val mockResponse = MockHttpServletResponse()
resolvedView.render(null, mockRequest, mockResponse)
return mockResponse.contentAsString
}
}
我在创建了一个模板 resources/templates/activity.html
. 但是当我们排队的时候 mockResponse.contentAsString
如果运行,则返回空字符串。
我是否遗漏了将模板呈现为字符串的任何特定步骤?
暂无答案!
目前还没有任何答案,快来回答吧!