码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot读取templates文件下的html

时间:2020-04-01 19:51:37      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:slf4j   ret   col   servlet   index   stream   一个   get   ati   

在不使用第三方jar包的情况下, Springboot不能直接访问templates下的静态页面, 需要加其他jar包依赖。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class PageController {
    private static ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
    private static final Logger log = LoggerFactory.getLogger(PageController.class);

    @RequestMapping("/")
    public void root(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/index.html").forward(request, response);
    }

    @RequestMapping("**.html")
    public void page(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStreamReader streamReader = null;
        try {
            String servletPath = request.getServletPath();
            log.info(request.getMethod() + " " + servletPath);
            String filePath = "templates" + servletPath;

            InputStream inputStream = classLoader.getResourceAsStream(filePath);
            if (inputStream == null) {
                response.sendError(404);
                return;
            }
            streamReader = new InputStreamReader(inputStream);
            PrintWriter printWriter = response.getWriter();
            response.setContentType("text/html");

            int readChar;
            while ((readChar = streamReader.read()) != -1) {
                printWriter.write(readChar);
            }
            printWriter.flush();
        } finally {
            if (streamReader != null) streamReader.close();
        }
    }
}

* 小白一个,如有错漏之处,敬请指正。

Springboot读取templates文件下的html

标签:slf4j   ret   col   servlet   index   stream   一个   get   ati   

原文地址:https://www.cnblogs.com/istruth/p/12614534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!