一、----------------------得到数据的测试的action类
package com.cm12530.quannei.action;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.cm12530.quannei.base.action.BaseAction;
import com.cm12530.quannei.base.util.XmlCommon;
import com.cm12530.quannei.common.NewsCommon;
import com.cm12530.quannei.common.PictureCommon;
import com.cm12530.quannei.common.ReverseSort;
import com.cm12530.quannei.common.StarCommon;
import com.cm12530.quannei.common.VideoCommon;
import com.cm12530.quannei.domain.News;
import com.cm12530.quannei.domain.Picture;
import com.cm12530.quannei.domain.Star;
import com.cm12530.quannei.domain.Video;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
@SuppressWarnings("serial")
public class PluginAction extends BaseAction {
private String urlPrefix;
public String getUrlPrefix() {
return urlPrefix;
}
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
@SuppressWarnings("unchecked")
public void getKeyWordList() {
String content = this.getRequest().getParameter("con");
content = XmlCommon.encode(content);
List list = getStarKeywordList(content);
//
// List list = new ArrayList();
// Star star1 = new Star();
// star1.setStarName("张学友");
// Star star2 = new Star();
// star2.setStarName("赵薇");
// Star star3 = new Star();
// star3.setStarName("许晴");
// Star star4 = new Star();
// star4.setStarName("韩庚");
// Star star5 = new Star();
// star5.setStarName("刘德华");
// Star star6 = new Star();
// star6.setStarName("巩俐");
// Star star7 = new Star();
// star7.setStarName("周杰伦");
// list.add(star1);
// list.add(star2);
// list.add(star3);
// list.add(star4);
// list.add(star5);
// list.add(star6);
// list.add(star7);
if(list!=null){
Collections.sort(list,new ReverseSort()); //排序算法
}
JSONArray commentJson = JSONArray.fromObject(list);
try {
this.renderJson(this.getResponse(), commentJson, null);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void getKeyWordContent() {
String keyword = this.getRequest().getParameter("k");
keyword = XmlCommon.encode(keyword);
String url = urlPrefix+"searchNews.action?keyword="+ keyword;
//String url = "D:/imigoo_workspace_2/smallWindow/src/news.xml";
Document doc = XmlCommon
.getDocument(url);
List newslist = null;
Star star = null;
if (doc != null) {
newslist = getNewsList(doc.getRootElement()); // 得到资讯集合
star = getStar(doc.getRootElement()); // 得到明星对象
}
List picList = getPictureList(keyword); // 得到图片集合
List videoList = getVideoList(keyword); // 得到视频集合
JSONArray jsonArr = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("newsList", newslist);
JSONObject obj2 = new JSONObject();
obj2.put("picList", picList);
JSONObject obj3 = new JSONObject();
obj3.put("videoList", videoList);
JSONObject obj4 = new JSONObject();
obj4.put("info", star);
jsonArr.add(obj1);
jsonArr.add(obj2);
jsonArr.add(obj3);
jsonArr.add(obj4);
try {
this.renderJson(this.getResponse(), jsonArr, null);
} catch (IOException e) {
e.printStackTrace();
}
}
/************
* 发送json封装返回数据
*
* @param response
* @param jsonArray
* @throws IOException
*/
public void renderJson(HttpServletResponse response, JSONArray jsonArray,
String text) throws IOException {
response.setHeader("CharSet", "UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/x-json;charset=UTF-8");
if (jsonArray != null && jsonArray.size() != 0) {
response.getWriter().print(jsonArray);
}
if (text != null && text.trim().length() != 0) {
response.getOutputStream().write(text.getBytes("UTF-8"));
}
}
/***********
* 得到资讯集合
*
* @param element
* @return
*/
public List<News> getNewsList(Element element) {
List<News> list = new NewsCommon().getNewsList(element);
return list;
}
/*********
* 得到明星对象
*
* @param element
* @return
*/
public Star getStar(Element element) {
Star star = new NewsCommon().getStar(element);
return star;
}
/**********
* 得到图片集合
*/
@SuppressWarnings("unchecked")
public List<Picture> getPictureList(String keyword) {
String url =urlPrefix+"searchImage.action?keyword="+ keyword;
//String url = "D:/imigoo_workspace_2/smallWindow/src/pic.xml";
Document doc = XmlCommon
.getDocument(url);
List piclist = null;
if (doc != null) {
piclist = new PictureCommon().getPictureList(doc.getRootElement());
}
return piclist;
}
/*******
* 得到视频集合
*
* @param element
* @return
*/
@SuppressWarnings("unchecked")
public List<Video> getVideoList(String keyword) {
VideoCommon vi = new VideoCommon();
String url = urlPrefix+"searchVideo.action?keyword="+ keyword;
//String url = "D:/imigoo_workspace_2/smallWindow/src/vedio.xml";
Document doc = XmlCommon.getDocument(url);
List list = null;
if (doc != null) {
list = vi.getVideoList(doc.getRootElement());
}
return list;
}
/***********
* 获得关键字列表
*
* @param element
* @return
* @throws IOException
* @throws HttpException
*/
public List<Star> getStarKeywordList(String str) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(
urlPrefix+"searchStarMark.action");// 使用POST方式提交数据
method.setRequestHeader("ContentType",
"application/x-www-form-urlencoded;charset=UTF-8");
method.addParameter("keyword", str);
InputStream returnStr = null;
Document doc = null;
try {
client.executeMethod(method);
returnStr = method.getResponseBodyAsStream();
SAXReader sr = new SAXReader();
doc = sr.read(returnStr);
} catch (IOException e1) {
e1.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 使用完成后要释放链接
method.releaseConnection();
}
List<Star> starlist = null;
if (doc != null) {
starlist = new StarCommon()
.getStarKeywordList(doc.getRootElement());
}
return starlist;
}
}
二,封装弹出层实现 datalib.js
var divch = 0; //初始化弹出层
var fw = new Object(); //创建一个对象
var gd;
//判断浏览器
fw.Browser = {
ie: /msie/.test(window.navigator.userAgent.toLowerCase()),
moz: /gecko/.test(window.navigator.userAgent.toLowerCase()),
opera: /opera/.test(window.navigator.userAgent.toLowerCase())
};
//得到当前浏览器高度
function dbwindowHeight() {
var E = document.documentElement;
return self.innerHeight || (E && E.clientHeight) || document.body.clientHeight;
}
//自定义获取对象的函数
fw.$ = function (s) {
return (typeof s == "object") ? s : document.getElementById(s);
};
//删除子节点的函数
fw.Element = {remove:function () {
for (var i = 0; i < arguments.length; i++) {
try {
fw.$(arguments[i]).parentNode.removeChild(fw.$(arguments[i]));
}
catch (e) {
}
}
}};
//切换弹出层newDiv的导航条
function tab(){
var obj= document.getElementById("box").childNodes;
var Arr=[];
var Arr2=[];
for(var i=0;i<obj.length;i++){
if(obj[i].className){
Arr.push(obj[i]);
}
}
var btn=Arr[0].getElementsByTagName("a");
var info=Arr[1].childNodes;
for(var j=0;j<info.length;j++){
if(info[j].className){
Arr2.push(info[j]);
}
}
btn[0].onmouseover=function(){
btn[0].className="quannei_selected";
btn[1].className="quannei_default";
btn[2].className="quannei_default";
Arr2[0].style.display="block";
Arr2[1].style.display="none";
Arr2[2].style.display="none";
}
btn[1].onmouseover=function(){
btn[1].className="quannei_selected";
btn[0].className="quannei_default";
btn[2].className="quannei_default";
Arr2[0].style.display="none";
Arr2[1].style.display="block";
Arr2[2].style.display="none";
}
btn[2].onmouseover=function(){
btn[2].className="quannei_selected";
btn[1].className="quannei_default";
btn[0].Name="quannei_default";
Arr2[0].style.display="none";
Arr2[1].style.display="none";
Arr2[2].style.display="block";
}
}
var xmlhttp=createXmlHttpRequest(); //XmlHttpRequest 对象;
fw.load = function (o){
var parameters ="k="+o.innerHTML+"&timeStamp="+new Date().getTime();//传递的参数
if(xmlhttp){
//浏览器跨域问题的判断
if(window.netscape && netscape.security.PrivilegeManager.enablePrivilege)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
catch (e)
{
//alert("抱歉!您的浏览器暂时不支持娱乐小窗。\n请在浏览器地址栏输入“about:config”并回车\n后将 [signed.applets.codebase_principal_support]设置为'true',点击“加入收藏”后忽略安全提示,即可设置成功。");
}
}
xmlhttp.onreadystatechange = function(){callbacktwo(o);}
try{
//POST方式请求的代码
xmlhttp.open("POST","http://www.quannei.cn/smallWindow/plugin!getKeyWordContent.action", true);
//POST方式需要自己设置http的请求头
xmlhttp.setRequestHeader("cache-control","no-cache");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}catch(e){
//if(window.ActiveXObject)
// alert("抱歉!您的浏览器暂时不支持娱乐小窗。\n请把浏览器安全设置里'通过域访问数据源'修改为'启用'")
}
}
}
//构建浮动框,并展示关键字返回的接口数据内容
function callbacktwo(o){
var starName = encodeURI(o.innerHTML);
if(xmlhttp.readyState == 4|| xmlhttp.readyState=="complete")
{
if(xmlhttp.status == 200)
{
retxt = xmlhttp.responseText;
var data = eval('('+retxt+')');
//此处是送json中获得后台对应封装的list集合
var news = data[0].newsList;
var pic = data[1].picList;
var video = data[2].videoList;
var info = data[3].info;
if (divch == 0) {
var parDiv = document.createElement("div");
var newDiv = document.createElement("div");
parDiv.id = "plugin_newDiv";
parDiv.style.position = "absolute";
parDiv.onmouseover = jtime;
parDiv.onmouseout = Judge;
newDiv.className = "quannei_msg";
wh = dbwindowHeight();
sWidth=document.body.scrollWidth;
//控制浮动框的位置
var h = 300;;
var dbt = o.offsetTop;
var dbl = o.offsetLeft;
var ofH = o.offsetHeight;
while (o = o.offsetParent) {
dbl += o.offsetLeft;
dbt += o.offsetTop;
}
var bt = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
var b = wh - (dbt - bt) - ofH;
if (b > h) {
h = dbt + ofH;
} else {
h = dbt - h;
}
parDiv.style.top = h + 5 + "px";
if(dbl>sWidth/2){
parDiv.style.left = dbl -380 + "px";
}else {
parDiv.style.left = dbl +20+ "px";
}
var ihtml = "";
ihtml+='<div class="quannei_m_c" id="box"><div class="quannei_tab">'
+'<a class="quannei_selected" href="javascript:void(0);" >资讯</a>'
+'<a class="quannei_default" href="javascript:void(0);" >图片</a>'
+'<a class="quannei_default" href="javascript:void(0);" >视频</a>'
+'<a href="http://www.quannei.cn/information.action?type=2&q='+starName+'" target="_blank">资料</a>'
+'<a href="http://www.quannei.cn/web/relationship/relationFull.jsp?q='+starName+'" target="_blank">关系</a>'
+'<a href="http://www.quannei.cn/queryStarWorks.action?type=2&keyword='+starName+'" target="_blank">作品</a>'
ihtml+='</div>'
ihtml+='<div class="quannei_m_c_c">'
ihtml+='<div id="quannei_news" class="quannei_news">'
ihtml+='<div class="quannei_news_img">'
if(info.image==''){
ihtml+='<img alt="" title="" src="http://www.quannei.cn/smallWindow/images/novideo.jpg " />'
}else{
ihtml+='<img alt="" title="" src=\"'+info.image+'\" onerror="this.src=\'http://www.quannei.cn/smallWindow/images/novideo.jpg\'"/>'
}
ihtml+='<h3>'+info.starName+'</h3>'
ihtml+='</div>'
ihtml+='<ul>'
for(var i=0;i<news.length;i++){
ihtml+='<li><a href=\"'+news[i].url +'\" target=\"_blank\" title=\"'+news[i].title+'\"/>'
ihtml+=news[i].title.sub(30);
ihtml+='</a></li>'
}
ihtml+='</ul>'
+'<div class="quannei_more">'
+'<a href="http://www.quannei.cn/news.action?type=2&q='+starName+'" target=\"_blank\">更多</a>'
+'</div>'
ihtml+='</div>'
ihtml+='<div class="quannei_photo dn">'
ihtml+='<ul>'
for(var i=0;i<pic.length;i++){
ihtml+='<li>'
ihtml+='<a href=\"'+pic[i].url+'\" target=\"_blank\">'
if(pic[i].url==''){
ihtml+='<img alt=\"'+pic[i].title+'\" title=\"'+pic[i].title+'\" src="http://www.quannei.cn/smallWindow/images/novideo.jpg " />'
}else{
ihtml+='<img alt=\"'+pic[i].title+'\" title=\"'+pic[i].title+'\" src=\"'+pic[i].url+'\" onerror="this.src=\'http://www.quannei.cn/smallWindow/images/novideo.jpg\'"/>'
}
ihtml+='<strong title=\"'+pic[i].title+'\">'+pic[i].title.sub(8)+'</strong>'
ihtml+='</a>'
ihtml+='</li>'
}
ihtml+='</ul>'
ihtml+='<div class="quannei_more">'
ihtml+='<a href="http://www.quannei.cn/picture.action?type=2&q='+starName+'" target="_blank">更多</a>'
ihtml+='</div>'
ihtml+='</div>'
ihtml+='<div class="quannei_photo dn">'
ihtml+='<ul>'
for(var i=0;i<video.length;i++){
ihtml+='<li>'
ihtml+='<a href=\"'+video[i].url+'\" target=\"_blank\">'
if(video[i].images[0].imageUrl==''||video[i].images[0].imageUrl==null){
ihtml+='<img title=\"'+video[i].title+'\" src="http://www.quannei.cn/smallWindow/images/novideo.jpg " />'
}else{
ihtml+='<img title=\"'+video[i].title+'\" src=\"'+video[i].images[0].imageUrl+'\" onerror="this.src=\'http://www.quannei.cn/smallWindow/images/novideo.jpg \'"/>'
}
ihtml+='<strong title=\"'+video[i].title+'\">'+video[i].title.sub(8)+'</strong>'
ihtml+='</a>'
ihtml+='</li>'
}
ihtml+='</ul>'
ihtml+='<div class="quannei_more">'
ihtml+='<a href="http://www.quannei.cn/video.action?type=2&q='+starName+'" target="_blank">更多</a>'
ihtml+='</div>'
ihtml+='</div>'
ihtml +='</div>';
ihtml +='<div class="quannei_cp">'
+'圈内<a href="http://www.quannei.cn/index.jsp" target="_blank">www.quannei.cn</a>'
ihtml +='</div>'
ihtml += '</div>'
newDiv.innerHTML = ihtml;
parDiv.appendChild(newDiv);
document.body.appendChild(parDiv);
divch = 1;
tab(); //此处调用弹出层切换导航条的函数
}
// alert(msg);
} else {
//alert("XML数据格式错误,原始文本内容为:" + xmlhttp.responseText);
}
}
}
var db_gtime = null;
var docEle = function () {
return document.getElementById(arguments[0]) || false;
};
var jtime = function () {
clearTimeout(db_gtime);
};
function openNewDiv(o) {
if (docEle("plugin_newDiv")) {
document.body.removeChild(docEle("plugin_newDiv"));
}
divch = 0;
clearTimeout(db_gtime);
fw.load(o);
}
function delDiv() {
if (docEle("plugin_newDiv")) {
document.body.removeChild(docEle("plugin_newDiv"));
}
divch = 0;
}
function Judge() {
db_gtime = setTimeout(delDiv, 800);
}
/**
* 使用POST方式请求
* 利用XMLHttpRequest对象接受与处理XML数据
*/
//创建 XmllHttpRequest 对象
function createXmlHttpRequest(){
var xmlHttp;
if(window.ActiveXObject){
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
try
{
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
alert("建立XMLHttpRequest object错误。");
else
return xmlHttp;
}
var xmlHttpReq = createXmlHttpRequest();
//讲文档整个内容传给接口数据分析,得到关键字列表
window.onload = function verify()
{
var content = document.body.innerHTML;
//filterContent1 = filterContent.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
var str=content.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g, "");
//var filterContent = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
// alert(str);
var parameters = "con="+str+"&timeStamp="+new Date().getTime();
if(xmlHttpReq)
{ //浏览器跨域问题的判断
if(window.netscape && netscape.security.PrivilegeManager.enablePrivilege)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e)
{
//alert("抱歉!您的浏览器暂时不支持娱乐小窗。\n请在浏览器地址栏输入“about:config”并回车\n后将 [signed.applets.codebase_principal_support]设置为'true',点击“加入收藏”后忽略安全提示,即可设置成功。");
}
}
xmlHttpReq.onreadystatechange = function(){callbackone(content);}
try{
//POST方式请求的代码
xmlHttpReq.open("POST","http://www.quannei.cn/smallWindow/plugin!getKeyWordList.action", true);
//POST方式需要自己设置http的请求头
xmlHttpReq.setRequestHeader("cache-control","no-cache");
xmlHttpReq.setRequestHeader("Content-length", parameters.length);
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.send(parameters);
}catch(e){
// if(window.ActiveXObject)
// alert("抱歉!您的浏览器暂时不支持娱乐小窗。\n请把浏览器安全设置里'通过域访问数据源'修改为'启用'");
}
}
}
//得到关键字列表,并且将内容中关键字标红
function callbackone(content)
{
var txt = "";
if(xmlHttpReq.readyState == 4||xmlHttpReq.readyState=="complete")
{
if(xmlHttpReq.status == 200)
{
txt = xmlHttpReq.responseText;
alert(txt);
if(txt!=''){
var remsg = eval('('+txt+')');
var body = document.getElementsByTagName("body")[0];
//标红函数,如果第三个参数为false则标第一个,如果为true则标全部
if(remsg!=''){
mark(body,remsg,false);
}
}
} else {
//alert("XML数据格式错误,原始文本内容为:" + xmlhttp.responseText);
}
}
}
function trim(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function mark(ele,stars,isMarkAll){
var d;
//如果传入的是文字 则转换成节点
if(typeof ele == 'string'){
d = document.createElement('div');
d.innerHTML = ele;
}else{
//否则直接引用
d = ele;
}
//遍历所有文档结点
var childNodes = d.childNodes;
for (var i = 0; i < childNodes.length ; i ++) {
var c = childNodes[i];
switch(c.nodeType) {
case 1:
if(c.nodeValue && trim(c.nodeValue).length == 0) break;
mark(c,stars,isMarkAll); break; //递归节点
case 3:
if (trim(c.nodeValue).length == 0)break;
var text_ = c.nodeValue;
for(var j = 0;j < stars.length;j++){
var pattern;
var starName = stars[j].starName;
if(isMarkAll){//如果标红全部
pattern = new RegExp(starName,'ig');
}else{//如果标红第一个
pattern = new RegExp(starName,'i');
if(pattern.test(text_)){
stars.splice(j,1);//移除无素,防止后面内容再次被标红
//j = j-1;//迭代下标-1
}
}
var index_ = text_.indexOf(starName);
var subpre = text_.substring(index_-1,index_);
//alert(subpre);
if(subpre!='>'){
text_ = text_.replace(pattern,"<strong id=\'replaceName\' style=\'color:red;cursor:pointer;\' onmouseover=\'openNewDiv(this);return false;\' onmouseout=\'Judge();return false;\'>"+starName+"</strong>");
}
}
var p_ = document.createElement('p');
p_.innerHTML = text_;
i += p_.childNodes.length-1;
while(p_.childNodes.length > 0){
d.insertBefore(p_.childNodes[0],c);
}
d.removeChild(c);
break;
}
}
}
/**
* 多关键字查询标红,避免后面的关键字成为特殊的HTML语言代码
* @param str 网页的内容
* @param inputs 关键字集合
* @param resStr 标红后的结果
*/
function markAll(str,inputs, resStr){
var index=str.length;//用来做为标识,判断关键字的下标
var next="";//保存str中最先找到的关键字
var rmindex = "";
for (var i = inputs.length -1 ; i>= 0;i--) {
var theNext=inputs[i].starName;
var theIndex=str.indexOf(theNext);
if(theIndex==-1){//过滤掉无效关键字
inputs.splice(i,1);
}else if(theIndex<index){
index=theIndex;//替换下标
next=theNext;
rmindex = i;//记住json对象序号
}
}
//如果条件成立,表示串中已经没有可以被替换的关键字,否则递归处理
if(index==str.length){
resStr.append(str);
}else{
resStr.append(str.substring(0,index));
resStr.append("<strong id=\'replaceName\' style=\'color:red;\' onmouseover=\'openNewDiv(this);return false;\' onmouseout=\'Judge();return false;\'>" +str.substring(index,index+next.length)+ "</strong>");
//该方法只对第一个关键字标红 :如果说是去掉该方法的话就是对所有的关键字进行标红
inputs.splice(rmindex,1);
var str1=str.substring(index+next.length,str.length);
markAll(str1,inputs,resStr);//剩余的字符串继续替换
}
}
/**自定义StringBuffer类*/
function StringBuffer(){
this.data = [];
}
StringBuffer.prototype.append = function(){
this.data.push(arguments[0]);
return this;
}
StringBuffer.prototype.toString = function(){
return this.data.join("");
}
/**
**截取字符串
*/
String.prototype.sub = function(n) {
var r = /[^\x00-\xff]/g;
if(this.replace(r, "mm").length <= n) return this;
// n = n - 3;
var m = Math.floor(n/2);
for(var i=m; i<this.length; i++) {
if(this.substr(0, i).replace(r, "mm").length>=n) {
return this.substr(0, i) +"..."; }
} return this;
};
//根据索引值删除json数组中指定的数据
function delstr(index, dataArray){
var len=dataArray.length;
for(var i=0;i<len;i=i+1){
if(i==(index-1)){
for(var j=i+1;j<len;j=j+1){
//当前索引值后的数据都向前移
dataArray[j-1]=dataArray[j];
}
//移完之后,自身长度减1
dataArray.length--;
}
}
}
//引入css
document.write("<link rel='stylesheet' href='http://www.quannei.cn/smallWindow/css/msg.css' type='text/css' />");
/* |xGv00|295870ba552066345eb4815821b4836b */