意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

HTML 使用 Spring Boot 返回字符串而不是 .html 文件

来源:恒创科技 编辑:恒创科技编辑部
2024-04-15 06:00:44

要在Spring Boot中返回字符串而不是.html文件,您可以使用@Controller@ResponseBody注解,以下是一个简单的示例:

1、创建一个名为StringController的控制器类,并使用@Controller注解标记它。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StringController {
}

2、在StringController类中添加一个方法,该方法使用@RequestMapping注解映射到特定的URL路径,并使用@ResponseBody注解返回字符串。


HTML 使用 Spring Boot 返回字符串而不是 .html 文件

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StringController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "<h1>Hello, World!</h1>";
    }
}

在这个例子中,当用户访问/hello路径时,将返回一个包含小标题“Hello, World!”的HTML字符串。

如果您想要返回一个单元表格,可以使用以下代码:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StringController {
    @RequestMapping("/table")
    @ResponseBody
    public String table() {
        return "<table border='1'><tr><th>Header 1</th><th>Header 2</th></tr><tr><td>Row 1, Cell 1</td><td>Row 1, Cell 2</td></tr><tr><td>Row 2, Cell 1</td><td>Row 2, Cell 2</td></tr></table>";
    }
}

这将返回一个包含两列和两行的简单表格。

上一篇: Python count函数的用法 下一篇: HTML &amp;#8211; HTML拖放可排序表格