面的例子说明了如何使用 Spring MVC 框架来编写一个简单的基于 web 的应用程序,它可以在 <mvc:resources> 标签的帮助下访问静态页面和动态页面。为了开始使用它,让我们在恰当的位置使用 Eclipse IDE,然后按照下面的步骤使用 Spring 的 Web 框架来开发一个动态的基于表单的 Web 应用程序:
这里是 WebController.java 文件的内容:
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value="/index", method=RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value="/staticPage", method=RequestMethod.GET)
public String redirect() {
return "redirect:/pages/final.htm";
}
}
下面是 Spring Web 配置文件 web.xml 的内容
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Page Redirection</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
下面是另一个 Spring Web 配置文件 HelloWeb-servlet.xml 的内容
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.tutorialspoint" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" /> <mvc:annotation-driven/> </beans>
在这里,<mvc:resources..../> 标签被用来映射静态页面。 mapping 属性必须是一个指定一个 http 请求的 URL 模式的 Ant 模式。 location 属性必须指定一个或者多个具有包含图片,样式表,JavaScript 和其他静态内容的静态页面的资源目录位置。多个资源位置可以使用逗号分隔这些值的列表来被指定。
下面是 Spring 视图文件 WEB-INF/jsp/index.jsp 的内容。这将是一个登陆页面,这个页面将发送一个请求来访问 staticPage 的 service 方法,它将重定向这个请求到 WEB-INF/pages 文件夹中的一个可用的静态页面。
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method="GET" action="/HelloWeb/staticPage"> <table> <tr> <td> <input type="submit" value="Get HTML Page"/> </td> </tr> </table> </form:form> </body> </html>
下面是 Spring 视图文件 WEB-INF/pages/final.htm 的内容。
<html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html>
最后,下面是包含在你的 web 应用程序中的 Spring 和其他库的列表。你仅仅需要将这些文件拖拽到 WebContent/WEB-INF/lib 文件夹中。
一旦你完成了创建源代码和配置文件后,导出你的应用程序。右键单击你的应用程序,并且使用 Export > WAR File 选项,并且在 Tomcat 的 webapps 文件夹中保存你的 HelloWeb.war 文件。
现在启动你的 Tomcat 服务器,并且确保你能够使用标准的浏览器访问 webapps 文件夹中的其他 web 页面。现在尝试访问该 URL http://localhost:8080/HelloWeb/index。 如果你的 Spring Web 应用程序一切都正常,你应该看到下面的结果:
单击 “Get HTML Page” 按钮来访问 staticPage 中的 service 方法中提到的一个静态页面。如果你的 Spring Web 应用程序一切都正常,你应该看到下面的结果:
一期给大家详解下页面静态化
1、静态化页面是什么?
php脚本把这些渲染出来。这个是时候页面是动态显示,前台展示的数据页面是动态,静态化页面就是将这个页面直接转成.html静态的页面,这个时候页面显示的时候不再是动态的,只有等页面只有更新数据的时候才会再次缓存新的数据到静态文件上。简单讲的可以这样子理解。
关于静态化的优点,这边不会在具体的介绍,下次有机会的话给大家讲下为什么要静态化页面,目前可以这样子理解就是静态化后的页面访问速度变得更快,大流量访问减少延迟。
下面直接代码演示如何写静态化页面,以下已php语言为例子
静态化写法
ob_start()这个php自带的函数 开启缓存
(1)第一种写法是通过ob_start()缓存来输出
在php文件中编写html代码,然后用bo_get_content获取到,然后输出到html文件,类似于:
<?php
ob_start(); //打开输出控制缓存
echo "<html><head><title>test页面</title></head><body>Hello world</body></html>";
$out=ob_get_contents(); //获取缓冲区的内容
ob_end_clean(); //关闭输出缓存
$fps=fopen("demo.html", "w");//打开demo.html文件开启写入权限
if (!$fps) {
echo "error";die;
} else {
fwrite($fps, $out); //写入文件
fclose($fps); //关闭文件
echo "success";
}
?>
上面这种写法比较混乱,语法结构不是很好,也不好维护,不推荐使用
(2)先写好静态文件,在使用替换语法更新内容
我们首先创建好一个静态文件,要替换的文件部分标出来,如{title},在php程序中用file_get_content获取html文件的内容,然后进行替换,替换之后保存为静态文件。
静态页:
<!DOCTYPE html>
<html>
<head>
<title>{th_title}</title>
</head>
<body>
<div class="">
<h1>{title}</h1>
<div class="author">{author}</div>
<div class="date">{add_time}</div>
<div>
{content}
</div>
</div>
</body>
</html>
这样子我们就已经写好了静态的文件
php文件替换:
$path="a.html";
$content=file_get_contents($path); //加载模板
//我们使用str_replace 函数 进行替换
$content=str_replace('{th_title}',$title);
$dir=$path ."/html/";
//判断文件是否存在
if (!file_exists($dir)) {
mkdir($dir);
}
$filename=$dir.'/'.$filename; //这里就不判断html是否存在了,因为写入会覆盖
$result=file_put_contents($filename,$content);//写入内容到对应静态文件中
上面的代码操作
我们需要先使用file_get_contents获取模板页的内容,然后将读取到的文件再使用str_replace进行标签的替换,最后再通过file_pu_contents写入到新文件即可。然后将文件转成的html。
页面的静态化操作就是这么简单,有什么疑问的话可以下面留言。
pring Boot中,你可能想要基于动态内容生成静态HTML页面。有几种方法可以实现这一目标,以下是其中的一些方法:
下面是一个使用Thymeleaf的简单示例:
@Service
public class StaticHtmlGeneratorService {
@Autowired
private TemplateEngine templateEngine;
@Autowired
private ApplicationContext applicationContext;
public void generateStaticHtml(String templateName, Map<String, Object> context, String outputPath) {
Context thContext=new Context();
thContext.setVariables(context);
String processedHtml=templateEngine.process(templateName, thContext);
try (BufferedWriter writer=new BufferedWriter(new FileWriter(outputPath))) {
writer.write(processedHtml);
} catch (IOException e) {
// Handle exception
}
}
}这段代码不是完整的实现,因为TemplateEngine类并不是Spring Boot标准库中的一部分。在实际应用中,你会使用具体的模板引擎的API(例如Thymeleaf的TemplateEngine),并相应地调整代码。
实际上,Spring Boot集成Thymeleaf后,你会这样使用Thymeleaf的API:
@Autowired
private SpringTemplateEngine templateEngine;
public void generateStaticHtml(String templateName, Map<String, Object> contextVars, String outputPath) {
Context context=new Context();
context.setVariables(contextVars);
String processedHtml=templateEngine.process(templateName, context);
// Write the processedHtml to a file
// ...
}public void generateStaticHtmlWithJsoup(String title, String bodyContent, String outputPath) throws IOException {
Document doc=Jsoup.parse("<html><head><title></title></head><body></body></html>");
doc.title(title);
doc.body().append(bodyContent);
// 美化输出(Pretty-print)
doc.outputSettings().prettyPrint(true);
// 写入文件
Files.write(Paths.get(outputPath), doc.outerHtml().getBytes(StandardCharsets.UTF_8));
}@Autowired
private RestTemplate restTemplate;
public void generateStaticHtmlFromWebService(String url, String outputPath) throws IOException {
ResponseEntity<String> response=restTemplate.getForEntity(url, String.class);
if (response.getStatusCode()==HttpStatus.OK) {
Files.write(Paths.get(outputPath), response.getBody().getBytes(StandardCharsets.UTF_8));
}
}在生成静态HTML时,请考虑以下几点:
*请认真填写需求信息,我们会在24小时内与您取得联系。