简体   繁体   中英

Spring Boot addObject not working correctly

i am trying to display a string in springboot web page but it,s not working correctly !

controller

@Controller
public controller {
    @RequestMapping("/")
    public ModelAndView get(){
        ModelAndView model = new ModelAndView("index.html");
        String name = "World";
        model.addObject("name",name);
        return model;
    }
}

index.html

<html>
<body>
     <h1>Hello <span th:text="${name}"></span></h1>
</body>
</html>

it works like this

在此处输入图像描述

    @Controller
    public controller {
        @RequestMapping("/")
        public ModelAndView get(){
            ModelAndView model = new ModelAndView("index");
            String name = "World";
            model.addObject("name",name);
            return model;
        }
    }

Test by removing the.html Also add th="http://www.thymeleaf.org" like below.

   <html xmlns:th="http://www.thymeleaf.org">
   <h1>Hello th:text="${name}"></h1>

Try removing the span or correctly add the content inside the span. Thank you

You don't need to change anything in java classes and even you don't need to remove the span in the HTML file. Check with the namespace in the HTML. The following is working without any issue with spring-boot <2.2.9.RELEASE> and using the thymeleaf template engine.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {
  
    @RequestMapping("/")
    public ModelAndView get(){
        ModelAndView model = new ModelAndView("index.html");
        String name = "World";
        model.addObject("name",name);
        return model;
    }
    
}

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>test</title>
</head>

<body>
    <h1>
        Hello <span th:text="${name}"></span>
    </h1>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM