Flask接口签名sign原理与实例代码浅析
306
2022-12-10
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.classhttp://);
@RequestMapping("/")
public void root(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/index.html").forward(request, response);
}
@RequestMapping("**.html")
public void page(HttpServletRequest requhttp://est, 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();
}
}
QwaYP}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~