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 = DefaultClassLoader();
private static final Logger log = Logger(PageController.class);
@RequestMapping("/")
public void root(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@RequestMapping("**.html")
public void page(HttpServletRequest request, HttpServletResponse response) throws IOException {
InputStreamReader streamReader = null;
try {
String servletPath = ServletPath();
log.Method() + " " + servletPath);
String filePath = "templates" + servletPath;
InputStream inputStream = ResourceAsStream(filePath);
if (inputStream == null) {
response.sendError(404);
return;
}
streamReader = new InputStreamReader(inputStream);
PrintWriter printWriter = Writer();
spring怎么读多个文件response.setContentType("text/html");
int readChar;
while ((readChar = ad()) != -1) {
printWriter.write(readChar);
}
printWriter.flush();
} finally {
if (streamReader != null) streamReader.close();
}
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。