您的位置:首页 > Web前端 > HTML

Word转换Html后分页展示--第二部分

2015-01-11 22:35 513 查看
这篇文章继续上一篇”Word转换Html后分页展示--第一部分“

实现

2. 当浏览器打开Html页面后需要执行一段计算分页的js,这段js是在生成Html后通过改写加入的。下面是上传Servlet

package com.word.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import com.word.jacob.JacobUtil;
import com.word.websocket.WebSocketMessageInboundPool;

public class UpLoadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String path = request.getRealPath("/upload")+"\\";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

for(FileItem item : list) {
String name = item.getFieldName();
if(item.isFormField()) {
request.setAttribute(name, item.getString());
} else {
//获取路径名
String value = item.getName();
int start = value.lastIndexOf("\\");
String filename = value.substring(start+1);
Long time = System.currentTimeMillis();
String htmlName = time+".html";
item.write(new File(path,filename));

//转换word
JacobUtil.wordConvertSingleton(path + filename, path + htmlName);

//改写html,加入js
File file = new File(path + htmlName);
String content = FileUtils.readFileToString(file,"GBK");
content = content.replaceAll("<head>", "<head><script src=\"jquery-1.9.0.min.js\"></script>");
content = content.replaceAll("</body>", "</body><script src=\"record.js\"></script>");

FileUtils.writeStringToFile(file , content);
WebSocketMessageInboundPool.sendMessage("upload\\"+htmlName);

//写空html
String htmlName2 = time+"_1.html";
File file2 = new File(path + htmlName2);
int div_start = content.indexOf("<div");
int div_end = content.substring(div_start).indexOf(">");
content = content.substring(0,div_start+div_end+1)+"</div></body><script src='read.js'></script></html>";
FileUtils.writeStringToFile(file2 , content);
response.sendRedirect("upload/"+htmlName2+"?id="+htmlName);
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
注意48—52行就是加入js,js内容如下

$(document).ready(function(){
setTimeout('calc()',1000);
})
//计算分页长度,提交分页信息和段落内容
function calc(){
var page = 0;
var height = 0;
var html = "";
var pathname = window.location.pathname
var id = pathname.substr(pathname.lastIndexOf("/")+1);
//获取div下的子元素,即<p>
$("div").children().each(function(i){
height += $(this).height();
//将<p>累加,当高度大于等于600像素时,向后台记录一次
html += $("<p1>").append($(this).clone()).html();
if(height >= 600){
page++;
height = 0;
$.post("../record", {id: id, pages: page, content: html});
html = "";
}
});
page++;
//记录最后一页内容,并关闭
$.post("../record", {id: id, pages: page, content: html},function(){
window.close();
});
}
3.保存很简单,我使用的Dbutils工具包,具体是servlet如下

package com.word.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.word.jdbc.DbUtil;

public class RecordServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
try {
DbUtil.insert("insert into pagecontent (id, pages, content) values (?, ?, ?)",
new Object[]{request.getParameter("id"),
request.getParameter("pages"),
request.getParameter("content")});
} catch (Exception e) {
e.printStackTrace();
}
}
}
插入和读取代码如下

package com.word.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

public class DbUtil {

public static void insert(String sql,Object[] objects) throws Exception{
QueryRunner run = new QueryRunner(true);
Connection connection = getConn();
try {
run.update(connection, sql, objects);
} catch (Exception e) {
DbUtils.close(connection);
}
}

/**
* 查询并返回Map
* @param sql
* @return
* @throws Exception
*/
public static Map<String, Object> queryForMap(String sql,Object[] objects) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
QueryRunner run = new QueryRunner(true);
Connection connection = getConn();
try {
map = (Map<String, Object>)run.query(connection, sql, getMapHandler(), objects);
} catch (Exception e) {
DbUtils.close(connection);
}
return map;
}

/**
* 获取MapHandler封装
* @return
*/
private static ResultSetHandler getMapHandler() {
ResultSetHandler handler = new MapHandler() {
public Map<String, Object> handle(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();

Map<String, Object> result = new HashMap<String, Object>();

String data = "";
for (int i = 0; i < cols; i++) {
if (rs.getObject(i + 1)==null) {
data= "";
}else {
data = rs.getObject(i + 1).toString();
}
result.put(meta.getColumnName(i + 1).toLowerCase(), data);
}

return result;
}
};
return handler;
}

/**
* 获取连接
* @return
* @throws Exception
*/
public static Connection getConn() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
return connection;
}
}
数据库表结构

DROP TABLE IF EXISTS `pagecontent`;
CREATE TABLE `pagecontent` (
`id` varchar(255) DEFAULT NULL,
`pages` int(11) DEFAULT NULL,
`content` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.生成查看界面其实在第2步时就完成了,见UpLoadServlet第57—63行。为什么这里要生成一个新的查看界面呢,因为要分页加载,所以需要一个空的界面。但这个界面不能通用,必须每次生成对应的。这个界面的内容是将Word转换生成的Html文件中Body清空,并加入分页读取的js方法,js如下

var pages = 1;
var fdiv;
var id;
$(document).ready(function(){
var href = window.location.href;
id = href.substr(href.indexOf("id=")+3);
//获取第一个div,并修改样式,加上有背景色和边框线
//修改宽度让其看上去是Word编辑界面大小
fdiv = $("div:first");
fdiv.attr("style",fdiv.attr("style")+";width:600;height: auto;margin: 0 auto;border: 1px solid #e3e3e3;background-color: white;margin-top:30px");
$.get("../view", {id: id, pages: pages},function(data){
fdiv.html(data);
});
var allpages = 17;
//滚动条加载
$(window).scroll(function(){
var scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
if ($(document).scrollTop() + document.body.clientHeight == scrollHeight) {
nextPage();
}
});
$("#index").html(pages);

})
function nextPage(){
pages++;
$.get("../view", {id: id, pages: pages},function(data){
fdiv.append(data);
$("#index").html(pages);
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: