对于内容网站形成于上个世纪九十年代,Web1.0时代开发的网站大多数都是基于内容网站,比如新闻类。开发这类的网站可以采用ASP、JSP、PHP技术,但是基于这类开发出来的网站,内容都是在阅读的时候实时的从数据库中读取的,对于搜索引擎网站,比如百度、Google的排行榜上排名往往很低,只有做成静态的HTML,才可以被搜索引擎加大排名。本文以一个内容发布网站来介绍基于模版的内容网站开发。
1.建立数据库
create database sec;
use sec
create table paper(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (id)
)AUTO_INCREMENT = 71;
系统很简单,就两个字段title文章标题,content文章内容,由于系统改造,以前的文章不收入现有数据库,所以编号从71开始。
2.建立后台数据收集系统
用Tomcat + jsp开发
输入页面:index.html
<!DOCTYPE HTML>
<html>
<head>
<title>文件输入</title>
<meta
http-equiv="Content-Type" content="text/html;
charset=utf-8">
</head>
<body>
<form action="index.jsp" method="post" >
<p>文件标题:<input type="text"
name="title" maxlength="200"></p>
<p>文件内容:<br><textarea
id="content" name="content" rows="30"
cols="100"></textarea></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
将内容存储到数据库中
index.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<%@ page language="java" %>
<%@ page import="java.sql.*"
%>
<%@ page
import="com.jerry.MySQLAccess" %>
<%
//设置字体
request.setCharacterEncoding("UTF-8");
//获取标题
String title = request.getParameter("title");
//获取内容
String content = request.getParameter("content");
//建立MySQLAccess对象
MySQLAccess mysql = new MySQLAccess();
try {
//建立数据库连接
Connection conn = mysql.connect();
//把插入内容放入字符串数组内
String[] value = {title, content};
//插入数据库
mysql.insert(conn,value);
//断开链接
mysql.disconnect(conn);
} catch (SQLException e1) {
e1.printStackTrace();
}
%>
<!DOCTYPE HTML>
<html>
<head>
<title>文件输入</title>
<meta
http-equiv="Content-Type" content="text/html;
charset=utf-8">
</head>
<body>
输入成功
</body>
</html>
3. Bean端开发
MySQLAccess对象通过Eclipse开发
pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jerry</groupId>
<artifactId>MySQL</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>9.0.0</version>
</dependency>
</dependencies>
</project>
版本用最新的9.0.0,由于下载速度很慢,可以通过浏览器从https://repo.maven.apache.org/maven2/下载,下载完毕放在.m2的相应目录下。
package com.jerry;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLAccess {
private static final String url = "jdbc:mysql://localhost:3306/sec";
private static final String user = "root";
private static final String password = "123456";
private static Statement stmt = null;
private static ResultSet rs;
//建立链接
public Connection connect() throws SQLException {
try {
//新版本改为"com.mysql.cj.jdbc.Driver"
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
return conn;
} catch (ClassNotFoundException e) {
System.out.println("JDBC 驱动未找到: " + e.getMessage());
} catch (SQLException e) {
System.out.println("数据库连接失败: " + e.getMessage());
}
return null;
}
//断开连接
public void disconnect(Connection conn) {
try {
if (rs != null) {
rs.close();
}
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
//插入数据
public boolean insert(Connection conn,String[] value) throws SQLException {
String insertString = "INSERT INTO paper (title, content) VALUES (?, ?);";
try {
PreparedStatement pstmt= conn.prepareStatement(insertString);
// 设置参数
pstmt.setString(1, value[0]);
pstmt.setString(2, value[1]);
// 执行插入操作
int affectedRows = pstmt.executeUpdate();
if (affectedRows == 1) {
return true;
}else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//查询数据
public ResultSet query(String Query) throws SQLException {
ResultSet rs = stmt.executeQuery(Query);
return rs;
}
//打印查询数据
public void print(ResultSet rs) throws SQLException {
while (rs.next()) {
System.out.println(rs.getString("columnname"));
}
}
}
由于包名为com.jerry,在Tomcat使用,将MySQLAccess.class放在%TOMECAT_HOME%\webapps\sec\WEB-INF\classes\com\jerry目录下。 4.开发模版替换程序
准备模版文件:
index_web.html:WEB首页,展示文件标题。
index_phone.html:手机首页,展示文件标题。
class_web.html:WEB首页,展示文件所有标题。
class_ phone.html:手机首页,展示文件所有标题。
content_ phone.html:WEB页,显示具体文件内容。
content_web.html:WEB页,显示具体文件内容。
把这些文件放在项目主目录.\source\下
RepeatFile.java
package com.jerry;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class RepeatFile {
private static FileInputStream fileInputStream = null;
private static InputStreamReader inputStreamReader = null;
//获取模版文件
public BufferedReader getFile(String myFile) {
try {
File file = new File(myFile);
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader;
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
}
return null;
}
//读取模版文件
public void readFile(BufferedReader bufferedReader) throws IOException {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
//关闭模版文件
public void closeFile(BufferedReader bufferedReader) throws IOException {
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
}
//替换HTML特殊字符,也为了防止XSS注入
public String repleatHTML(String sourceString) {
sourceString = sourceString.replaceAll("<", "<");
sourceString = sourceString.replaceAll(">", ">");
sourceString = sourceString.replaceAll(" ", " ");
sourceString = sourceString.replaceAll("\t", " ");
sourceString = sourceString.replaceAll("\n", " ");
sourceString = sourceString.replaceAll("\"", """);
sourceString = sourceString.replaceAll("’", "'");
return sourceString;
}
//替换文件
public void reapeFile(BufferedReader bufferedReader,String File) throws IOException {
//初始化变量
//存储读取到的当前行
String line;
//标题替换后的字符串
String replacement1 = "";
//内容替换后的字符串
String replacement2 = "";
//建立MySQLAccess对象变量
MySQLAccess mysql = new MySQLAccess();
try {
//SQL查询语句
String Query = "select id,title,content from paper";
//查询结果
ResultSet rs=mysql.query(Query);
//获得记录个数
ResultSetMetaData metaData = rs.getMetaData();
int number = metaData.getColumnCount();
//初始化将查询记录放入字符串数组
// id字符串数组
String[] id = new String[number];
//标题字符串数组
String[] title = new String[number];
//内容字符串数组
String[] content = new String[number];
int i = 0;
//替换后的目标文件
String destFile="";
//遍历查询记录
while (rs.next()) {
//将查询记录放入字符串数组内
id[i] = rs.getString("id");
title[i] = repleatHTML(rs.getString("title"));
content[i] = repleatHTML(rs.getString("content"));
//根据模版文件名,选择目标文件名和替换内容
switch(File) {
case(".\\source\\index_web.html"):
{
destFile = ".\\web\\index.html";
replacement1 += "<a href=\"class/c"+id[i]+".html\"target=\"_blank\">《"+title[i]+"》</a>";
break;
}
case(".\\source\\index_phone.html"):
{
destFile = ".\\phone\\index.html";
replacement1 += "<a href=\"class/c"+id[i]+".html\">《"+title[i]+"》</a><br>";
break;
}
case(".\\source\\class_web.html"):
{
destFile = ".\\web\\class.html";
replacement1 += "<li><a href=\"../class/c"+id[i]+".html\" target=\"_blank\">《"+title[i]+"》;</a></li>";
break;
}
case(".\\source\\class_phone.html"):
{
destFile = ".\\phone\\class.html";
replacement1 += "<li><a href=\"class/c"+id[i]+".html\">《"+title[i]+"》</a></li>";
break;
}
case(".\\source\\content_web.html"):
{
destFile = ".\\web\\c"+id[i]+".html";
replacement1 = title[i];
replacement2 = content[i];
break;
}
case(".\\source\\content_phone.html"):
{
destFile = ".\\phone\\c"+id[i]+".html";
replacement1 = title[i];
replacement2 = content[i];
break;
}
default:System.out.print("源文件名不正确");
}
i++;
}
//替换结果文件放入result,进行叠加
String result="";
while ((line = bufferedReader.readLine()) != null) {
//将当前读取行的最后加上回车
line = line+"\n";
//标题的替换标识符
String regex1 = "###1";
//内容的替换标识符
String regex2 = "###2";
//进行正则替换标题
line = line.replaceAll(regex1, replacement1);
//进行正则替换内容
result = result+line.replaceAll(regex2, replacement2);
}
//将替换后的内容写入目标文件
//打开目标文件
try (FileWriter writer = new FileWriter(destFile)) {
//写入目标文件
writer.write(result);
//关闭目标文件
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//处理文件
public void dealFile(String File) throws IOException {
//获取模本文件的bufferedReader
BufferedReader bufferedReader= getFile(File);
//获取模本文件
getFile(File);
//根据模本文件形成目标文件
reapeFile(bufferedReader,File);
//关闭模本文件
closeFile(bufferedReader);
}
//主函数
public static void main(String[] args) throws SQLException {
try {
//建立MySQLAccess对象变量
MySQLAccess mysql = new MySQLAccess();
//建立RepeatFile()对象变量
RepeatFile rf = new RepeatFile();
//建立数据库连接
Connection conn = mysql.connect();
//将要处理的模版文件名放在字符串数组内
String[] Files= {"index_web.html","index_phone.html","class_web.html","class_phone.html","content_web.html","content_phone.html"};
//遍历要处理的模版文件名的字符串数组
for (int i = 0; i < Files.length; i++) {
//统一加上目录
String file = ".\\source\\"+Files[i];
//处理文件
rf.dealFile(file);
}
//断开链接
mysql.disconnect(conn);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生成成功");
}
}
现在数据库中有两条数据
模版文件
某个模版文件中的替换标识
…
<li><a href="../class/c63.html"
target="_blank">《探索式软件测试》</a></li>
<li><a
href="../class/c66.html" target="_blank">《JMeter从入门到精通》</a></li>
<li><a
href="../class/c33.html" target="_blank">《APP软件专项测试》</a></li>
###1
…
形成的Web文件
形成的手机文件