1.创建本地maven项目 ,在pom.xml中配置freemarker的架包
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn</groupId>
<artifactId>fmarker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- freemarker的架包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
</dependencies>
</project>
2.在webapp的web-inf下的web.xml中配置freemarker的服务
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>fmarker</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!-- 模板的查找路径 从上下文根路径查找 模板 ftl-->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<!-- 是否不需要缓存 -->
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<!-- 最终显示是html -->
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html;charset=UTF-8</param-value>
</init-param>
<!-- FreeMarker settings: -->
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- 数字的格式 -->
<init-param>
<param-name>number_format</param-name>
<param-value>0.##</param-value>
</init-param>
<!-- servlet 容器启动时实例化 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
</web-app>
3.在webapp创建一个ftl文件,运行后可以直接在浏览器上输入它的路径
<#list 1..10 as i>
<#if (i_index+1)%2==0>
<font color=red>${i}</font><br/>
<#else>
<font color=green>${i}</font><br/>
</#if>
</#list>
4.应用maven ,在数据库创建一张表用来存储,以新闻发布为例 ,新闻的标题 ,内容 ,HTML路径 ,发布时间
4.创建新闻后端上传项目 ,在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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn</groupId>
<artifactId>news</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- 数据库的架包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- freemarker的架包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
</dependencies>
<!-- 设置字符集 -->
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
5.在src/main/resources中配置数据的资源文件 .properties
url=jdbc:mysql://localhost:3306/news
drclass=com.mysql.jdbc.Driver
userName=root
password=123456
6.配置调用数据源的方法
package model;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class Dbuit {
static Properties p = new Properties();
static{
InputStream is = Dbuit.class.getResourceAsStream("/jdbc.properties");
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/*获取链接
* @return
*
*/
public static Connection getConnection() throws Exception{
String url=p.getProperty("url");
String drclass=p.getProperty("drclass");
String userName=p.getProperty("userName");
String password=p.getProperty("password");
Class.forName(drclass);
//登录成功
Connection conn = DriverManager.getConnection(url,userName,password);
return conn;
}
//执行sql语句
public static int execute(String sql) throws Exception{
//连接数据库
Connection con=getConnection();
//预编译SQL语句
PreparedStatement pst=con.prepareStatement(sql);
//执行SQL语句
int i=pst.executeUpdate();
con.close();
pst.close();
return i;
}
//查询
public static List<Map> query(String sql) throws Exception{
//连接数据库
Connection con=getConnection();
//预编译SQL语句
PreparedStatement pst=con.prepareStatement(sql);
//执行SQL语句
ResultSet rs=pst.executeQuery();
//获取列名
ResultSetMetaData remd =rs.getMetaData();
List list=new ArrayList();
//获取列的个数
int columnCount =remd.getColumnCount();
while(rs.next()){
Map map= new HashMap();
for(int i=1;i<=columnCount;i++){
//获取列名
String colName=remd.getColumnName(i);
//获取列值
String colValue=rs.getString(i);
map.put(colName, colValue);
}
list.add(map);
}
con.close();
pst.close();
rs.close();
return list;
}
}
7.创建新闻上传,查询的方法
package model;
import java.util.List;
import java.util.Map;
public class Mynews {
//发布新闻
public void inserNews(String title,String content,String newspath,String createtime) throws Exception{
String sql="insert into mynews(title,content,htmlpath,createtime)values('"+title+"','"+content+"','"+newspath+"','"+createtime+"')";
Dbuit.execute(sql);
}
//查询新闻
public List<Map> queryNews() throws Exception{
String sql="select * from mynews";
return Dbuit.query(sql);
}
}
8.创建上传新闻的页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body align="center">
<h1><font color=blue>新闻发布</font></h1>
<form action="News" method="post">
标题:<input type="text" name="title"/><br/>
内容:<textarea rows="20" cols="100" name="content"></textarea><br/>
<input type="submit">
</form>
</body>
</html>
9.controller层servlet的调用
package controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import model.Mynews;
/**
* Servlet implementation class News
*/
public class News extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public News() {
// TODO Auto-generated constructor stub
}
//调用插入,查询的方法
Mynews my= new Mynews();
//设计时间格式
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//生成静态HTML存储的位置
public static final String HTML_DIR="E:\\html";
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符集
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//获取新闻的标题
String title=request.getParameter("title");
//获取新闻的内容
String content=request.getParameter("content");
//获取时间
Date date= new Date();
String dates=sdf.format(date);
//获取唯一的UUID
String uuid=UUID.randomUUID().toString();
try {
//生成HTML
Configuration config=new Configuration(Configuration.VERSION_2_3_23);
//模板文件的位置
config.setDirectoryForTemplateLoading(new File("src/main/resources"));
config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
//把值注入HTML
Map root = new HashMap();
root.put("title", title);
root.put("content", content);
root.put("createtime", dates);
////加载模板文件 -- 实例化模板对象
Template temp =config.getTemplate("news.ftl");
//文件的保存路径
String sa=HTML_DIR+"/"+(uuid)+".html";
Writer out =new OutputStreamWriter(new FileOutputStream(sa));
//文件的输出
temp.process(root, out);
out.flush();
out.close();
//新闻上传到数据库
my.inserNews(title, content, (uuid) + ".html", dates);
response.getWriter().println("发布成功...");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
10.新闻的模板
<div style="text-align:center;"><h1><font color=red>${title}</font><br/></h1></div>
${createtime}<br/>
${content}
11.创建前端freemarker项目,在本地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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn</groupId>
<artifactId>new</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- 配置数据库的架包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- 配置freemarker的架包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- 配置commons-io的架包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<!-- 设置字符集 -->
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
12.配置连接数据库的四要素,在src/main/resources中创建 .properties文件
url=jdbc:mysql://localhost:3306/news
drclass=com.mysql.jdbc.Driver
userName=root
password=123456
13.调用封装jdbc的方法类package model;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class Dbuit {
static Properties p = new Properties();
static{
InputStream is = Dbuit.class.getResourceAsStream("/jdbc.properties");
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/*获取链接
* @return
*
*/
public static Connection getConnection() throws Exception{
String url=p.getProperty("url");
String drclass=p.getProperty("drclass");
String userName=p.getProperty("userName");
String password=p.getProperty("password");
Class.forName(drclass);
//登录成功
Connection conn = DriverManager.getConnection(url,userName,password);
return conn;
}
//执行sql
public static int execute(String sql) throws Exception{
//连接数据库
Connection con=getConnection();
//预编译SQL语句
PreparedStatement pst=con.prepareStatement(sql);
//执行SQL语句
int i=pst.executeUpdate();
con.close();
pst.close();
return i;
}
//查询
public static List<Map> query(String sql) throws Exception{
//连接数据库
Connection con=getConnection();
//预编译SQL语句
PreparedStatement pst=con.prepareStatement(sql);
//执行SQL语句
ResultSet rs=pst.executeQuery();
//获取列名
ResultSetMetaData remd =rs.getMetaData();
List list=new ArrayList();
//获取列的个数
int columnCount =remd.getColumnCount();
while(rs.next()){
Map map= new HashMap();
for(int i=1;i<=columnCount;i++){
//获取列名
String colName=remd.getColumnName(i);
//获取列值
String colValue=rs.getString(i);
map.put(colName, colValue);
}
list.add(map);
}
con.close();
pst.close();
rs.close();
return list;
}
}
14.创建查询新闻的方法
package model;
import java.util.List;
import java.util.Map;
public class Mynews {
//查询
public List<Map> queryNews() throws Exception{
String sql="select * from mynews";
return Dbuit.query(sql);
}
}
15.刷新新闻页面
package main;
import java.util.Timer;
public class Index {
public static void main(String[] args) {
Timer ti= new Timer();
//new执行任务,执行时间,执行第一次之后多少时间之后执行下一次
ti.schedule(new MyTimerTask(), 1000,5000);
}
}
16.生成前端模板
<#list List as new>
<#-- 首页显示新闻的连接与标题-->
<a href="new?path=${new.htmlpath}">${new.title}</a><br/>
</#list>
17.生成前端首页
package main;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import model.Mynews;
public class MyTimerTask extends TimerTask{
//调用查询的方法
Mynews my= new Mynews();
public void run(){
try {
// 生成html
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
//模板文件的位置
cfg.setDirectoryForTemplateLoading(new File("src/main/resources"));
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
//获取所有的新闻
List<Map> result=my.queryNews();
Map root = new HashMap();
root.put("List", result);
//加载模板文件 -- 实例化模板对象
Template temp = cfg.getTemplate("index.ftl");
//生成首页页面的位置
String saveFile = "src/main/webapp/index.html";
//写入内容
Writer out = new OutputStreamWriter(new FileOutputStream(saveFile));
temp.process(root, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
18. 读取新闻的内容
package main;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class NewServler
*/
public class NewServler extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public NewServler() {
// TODO Auto-generated constructor stub
}
//新闻存储的位置
public static final String HTML_DIR = "E:\\html\\";
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取模板传过来的连接路径
String path=request.getParameter("path");
//完整的文件存储路径
String abs=HTML_DIR+path;
//读取存储的新闻内容
byte[] bt=FileUtils.readFileToByteArray(new File(abs));
//输出到首页连接
response.getOutputStream().write(bt);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
19.启动后台发布新闻项目,在运行前台新闻首页