后端返回的一个String我如何在前端界面接收请使用springmvc并举例
在Spring MVC中,可以使用@Controller注解来定义一个控制器类,使用@RequestMapping注解来定义该控制器类中的方法对应的URL。因此,可以在控制器方法中接收后端返回的String数据,然后将其传递给前端页面。
示例代码如下:
@Controller
public class MyController {
@RequestMapping("/getString")
public String getString(Model model) {
// 后端返回的字符串
String str = "Hello World!";
// 将字符串存入Model中,以便在前端页面中使用
model.addAttribute("str", str);
// 返回对应的前端页面
return "myPage";
}
}
在上述代码中,MyController类中的getString方法使用@RequestMapping注解来定义了URL为"/getString"。该方法将后端返回的字符串存入了Model中,并返回了名为"myPage"的前端页面。
在前端页面中,可以使用Thymeleaf模板引擎来显示后端传递过来的字符串。示例代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>My Page</title>
</head>
<body>
<h1 th:text="${str}"></h1>
</body>
</html>
在上述代码中,使用了Thymeleaf模板引擎的th:text属性来显示后端传递过来的字符串。在运行时,Thymeleaf会将该属性值替换为后端传递过来的字符串。
原文地址: https://www.cveoy.top/t/topic/Mq4 著作权归作者所有。请勿转载和采集!