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";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43742217/article/details/121880651