1. 程式人生 > 程式設計 >Springboot讀取templates檔案html程式碼例項

Springboot讀取templates檔案html程式碼例項

SpringBoot裡面沒有我們之前常規web開發的WebContent(WebApp),它只有src目錄

在src/main/resources下面有兩個資料夾,static和templates springboot預設 static中放靜態頁面,而templates中放動態頁面

在不使用第三方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();
    }
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。