面的例子說明了如何使用 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 頁面?,F在嘗試訪問該 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小時內與您取得聯系。