Springboot向静态页面写入数据,实现动态改变页面

在有模板的情况下不使用模板,可以使用重定向来返回页面。
文件写入需要先将字符串转换成byte[],转换方法content.getBytes(StandardCharsets.UTF_8)。
在程序执行结束的末尾一定要将输出流关闭。

@GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id){

        final GsWeather gsWeather = gsWeatherService.selectGsWeatherById(id);
        String content = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" +
                "<head>\n" +
                "    <th:block th:include=\"include :: header('修改出行气象')\" />\n" +
                "    <style>\n" +
                "        input{\n" +
                "            width:100%;\n" +
                "            border:none;\n" +
                "            text-align: center;\n" +
                "            outline-color: aqua;\n" +
                "        }\n" +
                "        span{\n" +
                "            display: inline-block;\n" +
                "            width:25%;\n" +
                "            text-align: center;\n" +
                "        }\n" +
                "        #table{\n" +
                "            width:80%;\n" +
                "            margin: 10px auto;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body class=\"white-bg\">\n" +
                "<input type=\"hidden\" id=\"id\" value=\""+gsWeather.getId()+"\">\n" +
                "<div id=\"table\" class=\"container-div\">"+gsWeather.getHtml()+
                "</div>\n" +
                "<th:block th:include=\"include :: footer\" />\n" +
                "</body>\n" +
                "</html>";
        //获取文件路径,解决部署时路径问题
        ClassPathResource resource = new ClassPathResource("detail.html");
        String path = resource.getPath();
        //获取文件
        File file = new File(path);
        //写入文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            //文件写入需要先将字符串转换成byte[]
            //转换方法content.getBytes(StandardCharsets.UTF_8)
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            fileOutputStream.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //在有模板的情况下不使用模板,可以使用重定向来返回页面
        return "redirect:/html/detail.html";
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值