【问题标题】:Thymeleaf with springboot and Scala not rendering HTML page带有springboot和Scala的Thymeleaf不呈现HTML页面
【发布时间】:2023-04-01 01:24:01
【问题描述】:

我在 Scala 中使用 Thymeleaf 和 Springboot。 当我从 HTML 页面发出 get 请求时,它会转到控制器并将下一个 HTML 文件名作为字符串而不是整个 HTML 返回。

我的 build.gradle

compile("org.thymeleaf:thymeleaf-spring4")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")  

我已经把所有的html放到了src/main/resources/templates

主 html

<html xmlns:th="http://www.thymeleaf.org">

<a href="#" th:href="@{/api/v1/users/userval}">Login</a>

控制器

@RestController 
@RequestMapping(value = Array("/api/v1/users"),produces = Array("text/html"))
class UserController {

@RequestMapping(method = Array(RequestMethod.POST))
@ResponseStatus(value = HttpStatus.CREATED)
def createUser(@Valid @RequestBody user:User) = {     

 UserRepository.populateUser(user)

}

 @RequestMapping(value=Array("/userval"),method = Array(RequestMethod.GET))
  def userLoginForm( model:Model) = {
   model.addAttribute("userLogin", new UserLogin())
  "login"}  

 @RequestMapping(value=Array("/userval"),method = Array(RequestMethod.POST))
  def getUser(@ModelAttribute  userLogin:UserLogin, bindingResult: BindingResult) = {
    "reservations"
  } 

在这里,当我单击主 HTML 中的登录链接时,我得到“登录”作为字符串而不是 login.html

【问题讨论】:

    标签: scala spring-boot thymeleaf


    【解决方案1】:

    如果您希望响应呈现视图,请使用 @Controller 而不是 @RestController 注释您的类

    @RestController 告诉 Spring 返回值是响应的主体,即不会发生视图渲染。这相当于用@Controller 注释类,用@ResponseBody 注释每个方法。

    【讨论】:

    • 我确实使用了@Controller,并将我的 html 页面放在了模板文件夹中,但仍然在 scala 中,它只是无法获取 html 页面,但是在 java 中相同的应用程序可以正常工作吗?
    • @sriharikalicharanTummala 这听起来像是一个不同的问题。最好将其作为一个单独的问题来解决,以便为某人提供足够的信息来重现该问题。
    • stackoverflow.com/questions/56761061/… ,成功了 抱歉打扰你@Andy Wilkinson
    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2016-04-17
    • 1970-01-01
    • 2013-12-03
    • 2017-05-15
    相关资源
    最近更新 更多