1.多附件上传以及判断个数
function isSameName()//判断上传的文件不能重复
{
var u=0; //附件个数
var s=0;
var filename = new Array();
var frm = document.getElementsByTagName('input');
for(var i=0;i<frm.length;i++){
if(frm[i].type == 'file')
{
var iname = frm[i].value;
var string_arr = iname.split("//");
filename[s] = string_arr[string_arr.length-1];
s++;
}
}
for(var s=0;s<filename.length;s++){
var tname = filename[s];
if(tname == '')
++u;
}
if(u == filename.length){
alert("请添加图片...");
return false;
}
for(var j=0;j<filename.length-1;j++){
var uname = filename[j];
for(var k=j+1;k<filename.length;k++)
{
var sname = filename[k];
if(uname != '' & sname != '') {
if (uname == sname)
{
alert("文件"+(j+1)+"和"+"文件"+(k+1)+"相同");
return false;
}
}
}
}
return true;
}
var i = 1;//增加上传的文件
function addFile(dvID, inputNamePrefix)
{
if(i<6){
var dv = document.getElementById(dvID);
var file = document.createElement("input");
file.type = "file";
file.id = file.name = inputNamePrefix + i;
dv.appendChild(file);
var btn = document.createElement("input");
btn.type = "button";
btn.id = btn.name = "btn" + i;
btn.value = "删除" ;
btn.onclick = function() {
var b = document.getElementById(btn.id);
dv.removeChild(b.nextSibling); //remove <BR>
dv.removeChild(b.previousSibling); //file
dv.removeChild(b); //btn
--i;
}
dv.appendChild(btn);
dv.appendChild(document.createElement("BR"));
++i;}else{
alert("最多上传5个");
return false;
}
}
2.多用户可能同时操作一个文件的时候控制其查看只能一个人
主要是使用 listener监听器,大概如下
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import com.ucap.oapro.formpro.zhengwen.SingleWriteDocLogic;
public class FormproSessionAttributeListener implements HttpSessionAttributeListener
{
public void attributeAdded(HttpSessionBindingEvent se)
{
if("formprodocstat".equals(se.getName()))
{
System.out.println((new StringBuilder("se:----------attributeAdded----")).append((String)se.getValue()).toString()+"*"+(String)se.getSession().getAttribute(com.ucap.control.mfw.Constant.SESSION_SYS_USERID));
SingleWriteDocLogic.newInstance().checkAndSetDocState((String)se.getValue(),(String)se.getSession().getAttribute(com.ucap.control.mfw.Constant.SESSION_SYS_USERID));
}
}
public void attributeRemoved(HttpSessionBindingEvent se)
{
if("formprodocstat".equals(se.getName()))
{
System.out.println((new StringBuilder("se:----------attributeRemoved----")).append((String)se.getValue()).toString()+"*"+(String)se.getSession().getAttribute(com.ucap.control.mfw.Constant.SESSION_SYS_USERID));
SingleWriteDocLogic.newInstance().removeDoDocStatUseridByDatafilename((String)se.getValue(),(String)se.getSession().getAttribute(com.ucap.control.mfw.Constant.SESSION_SYS_USERID));
}
}
public void attributeReplaced(HttpSessionBindingEvent httpsessionbindingevent)
{
}
}
此类完成类在创建SESSION的时候做的工作,其他用户只要查看此SESSION中有东西就不能操作
session.setAttribute("formprodocstat",datafilename);//创建session
String nowmodifydocuserid = com.ucap.oapro.formpro.zhengwen.SingleWriteDocLogic.newInstance().getDoDocStatUseridByDatafilename(datafilename);
System.out.println("nowmodifydocuserid------------------------------:"+nowmodifydocuserid+"*"+(nowmodifydocuserid==null||nowmodifydocuserid.equals(userId))+"*"+userId);
boolean inmodifying = true;
if (nowmodifydocuserid==null||nowmodifydocuserid.equals("")||nowmodifydocuserid.equals(userId))
{
inmodifying = false;
}
在用户离开操作的时候去处SESSION,如下
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page language="java" import="java.sql.*,java.util.*,java.net.URLEncoder"%>
<%
String sessiondatafilename = request.getParameter("sessiondatafilename");
System.out.println("_________________fdsfdas__________"+sessiondatafilename);
if (sessiondatafilename!=null)
session.removeAttribute("formprodocstat");
request.getRequestDispatcher("dodocsession.jsp").forward(request,response);
return;
%>
3.遍例物理文件夹
String syspath = request.getRealPath("/") + "databak/" + dir;
File datafile = new File(syspath);
if (datafile.isDirectory()) {
File[] fs = datafile.listFiles();
if (fs == null) {
return mapping.findForward(ConstantDefine.FORWARD_SUCCESS);
} else {
for (int i = 0; i < fs.length; i++) {
filelist.add(fs[i].getName());
}
request.setAttribute("filelist",filelist);
}
}
这样在页面上就能得到filelist里面的值了
private static void del(File f) throws IOException {//完成递归删除文件,同样可以递归得到文件
if (f.isFile())
f.delete();
else if (f.isDirectory()) {
String[] files = f.list();
for (int i = 0; i < files.length; i++) {
del(new File(f.getAbsolutePath() + "//" + files[i]));
}
f.delete();
}
}
4.导出EXCEL(利用JXL控件)
页面的代码(主要是得到一个LIST)
<%--
*version:1.0
*createdate:2006 13:30:57
*Copyright: Berheley Tech Co,.ltd
* JSP页面功能描述: 输出Excel
* @author <a href="WangNanmailto:[email protected]">WangNan</a>
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/tld/valuelist.tld" prefix="vlh"%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="jxl.*" %>
<%@ page import="jxl.write.*" %>
<%@ page import="jxl.format.*" %>
<%@ page import="com.berheley.oa.persistence.model.tree.TAllArchive,com.berheley.common.ConstantEnumDefine.ArchiveType" %>
<%
//System.out.println("userId="+userId+",isManager="+isDocManger);
List reports = (List)request.getAttribute("reports");
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("Application/msexcel");
String fileName = java.net.URLEncoder.encode("文件修订记录","UTF-8");
response.setHeader("Content-disposition","inline; filename="+fileName+".xls");
//开始写入excel
//加标题
//标题字体
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.COURIER, 18, WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//字段字体
jxl.write.WritableFont wfc1 = new jxl.write.WritableFont(WritableFont.COURIER,10, WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfFC1 = new jxl.write.WritableCellFormat(wfc1);
wcfFC1.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//结果字体
jxl.write.WritableCellFormat wcfFC2 = new jxl.write.WritableCellFormat();
wcfFC2.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
WritableWorkbook wbook = Workbook.createWorkbook(response.getOutputStream());
//写sheet名称
WritableSheet wsheet = wbook.createSheet("文件修订记录", 0);
java.util.Date aaa=new java.util.Date();
java.text.SimpleDateFormat aSimpleDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String today = aSimpleDateFormat.format(aaa);
//加入字段名 设定列宽度
int column = 0;
wsheet.setColumnView(column,10);
wsheet.addCell(new jxl.write.Label(column++,3,"文件编号",wcfFC1));
wsheet.setColumnView(column,20);
wsheet.addCell(new jxl.write.Label(column++,3,"文件名称",wcfFC1));
wsheet.setColumnView(column,20);
wsheet.addCell(new jxl.write.Label(column++,3,"修订编号",wcfFC1));
wsheet.setColumnView(column,20);
wsheet.addCell(new jxl.write.Label(column++,3,"修订人",wcfFC1));
wsheet.setColumnView(column,15);
wsheet.addCell(new jxl.write.Label(column++,3,"修订时间",wcfFC1));
//加入标题
WritableFont wf_merge = new WritableFont(WritableFont.ARIAL,22,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,jxl.format.Colour.GREEN);
WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
wff_merge.setBackground(jxl.format.Colour.LIGHT_TURQUOISE);
wsheet.mergeCells(0,0,column-1,0);
wsheet.addCell(new Label(0,0,"文件修订记录",wff_merge));
wsheet.setRowView(0,800);
//加入打印时间
wsheet.addCell(new Label(column-2,1,"打印日期:"));
wsheet.addCell(new Label(column-1,1,today));
//下面开始输出结果
for(int i=0; i<reports.size();i++){
column = 0;
org.apache.commons.beanutils.BasicDynaBean archive =(org.apache.commons.beanutils.BasicDynaBean)reports.get(i);
String wenjianbiaoti = (String)archive.get("file_path");
System.out.println("file_path ==============================" + wenjianbiaoti);
wsheet.addCell(new Label(column++,i+4,(String)archive.get("file_path")==null?"":(String)archive.get("file_path"),wcfFC2));
wsheet.addCell(new Label(column++,i+4,(String)archive.get("titledetail")==null?"":(String)archive.get("titledetail"),wcfFC2));
wsheet.addCell(new Label(column++,i+4,(String)archive.get("xiudingbianhao")==null?"":(String)archive.get("xiudingbianhao"),wcfFC2));
wsheet.addCell(new Label(column++,i+4,(String)archive.get("createpeople")==null?"":(String)archive.get("createpeople"),wcfFC2));
wsheet.addCell(new Label(column++,i+4,(String)archive.get("createtime")==null?"":(String)archive.get("createtime"),wcfFC2));
}
//写入流中
wbook.write();
wbook.close();
response.getOutputStream().close();
%>
<%!
private String getLabel(String value){
ArchiveType[] array= ArchiveType.values();
for(int i=0;i<array.length;i++){
if(array[i].getValue().equals(value)){
return array[i].getLabel();
}
}
return "ERROR";
}
%>
如上的代码就完成了文件的导出EXCEL,很简单吧
5.像QQ一样弹出信息
<%@ page contentType="text/html; charset=utf-8" language="java" errorPage=""%>
<%@ page import="java.text.SimpleDateFormat,java.text.ParseException,java.util.Date" %>
<%@ page import="com.ucap.system.db.DataBase,com.ucap.system.db.DataBaseFactory,com.ucap.system.db.RecordSet" %>
<% String SOF_Host=request.getContextPath()+"/"; %>
<script language =javascript>
var titlePopup;
var len;
var tID;
function close(){
window.clearInterval(tID); window.titlePopup.hide();
}
function InitMsgBox(remind) {
var remind_value =remind.toString() ;
len = 0;
titlePopup=window.createPopup();
var titlePopupBody = titlePopup.document.body;
var titleContent = "";
titleContent = titleContent + "<table width='256' height='159' border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed'>";
titleContent = titleContent + "<tr><td background='images/tc_windows_01.gif' height='20'><div style='margin-right:10px;' align='right' ><img src='images/tc_windows_04.gif' onclick='parent.close();' onMouseOver='this.src=/"images/tc_windows_05.gif/"' onMouseOut='this.src=/"images/tc_windows_04.gif/"' /></div></td></tr>";
titleContent = titleContent + "<tr><td height='132' background='images/tc_windows_02.gif' valign='top'><div style='width:236px; margin-top:5px;margin-left:10px; '><br><font style='color:#0000FF; font-size:13px;line-height:14px;'>"
titleContent = titleContent + remind_value ;
titleContent = titleContent + "</font></div></td></tr>" ;
titleContent = titleContent + "<tr><td><img src='images/tc_windows_03.gif' width='256' height='7' /></td></tr>";
titleContent = titleContent + "</table>";
titlePopupBody.innerHTML = titleContent;
ShowMsgBox();
}
function MsgBox(){
if(len > 159){
titlePopup.show(document.body.clientWidth - 256, document.body.clientHeight - len, 256, len, top.document.body);
}else{
len += 4;
titlePopup.show(document.body.clientWidth - 256, document.body.clientHeight - len, 256, len, top.document.body);
}
}
function ShowMsgBox(){
tID = window.setInterval("MsgBox()",30);
}
</script>
<%
String userId = (String)request.getSession().getAttribute(com.ucap.control.mfw.Constant.SESSION_SYS_USERID);
String sql = "select top 1 * from TrainRemind order by createdate desc";
DataBase db= DataBaseFactory.getDataBase();
RecordSet rs =null ;
String date_1 ="";
String date_2 ="";
String remindperson = "";
String remind="";
if((rs=db.execSelect(sql)).next()){
date_1 =rs.getString("startdate");
date_2 =rs.getString("enddate");
remindperson =rs.getString("remindperson");
remind =rs.getString("reminddetail");
}else{
if(rs!=null)rs.close();
if(db!=null)db.close();
return;
}
if(rs!=null)rs.close();
if(db!=null)db.close();
//判断当前用户是否在被提醒列表当中
boolean isRemind = false ;
String [] personarray = remindperson.split(";");
for(int i=0;i<personarray.length;i++){
if(userId.equals(personarray[i])){
isRemind = true ;
break;
}
}
Date date = new Date();
Date startdate = new Date();
Date enddate = new Date();
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
try {
date=sdf.parse(sdf.format(date));
startdate = sdf.parse(date_1);
enddate = sdf.parse(date_2);
} catch (ParseException e) {
e.printStackTrace();
}
if( isRemind && (((startdate.before(date)) && ( enddate.after(date))) || (startdate.equals(date)) || (enddate.equals(date)))){
%>
<script language=javascript>window.setTimeout('InitMsgBox("<%=remind%>")',3000);</script>
<%
}
%>
6.利用DIV进行隐藏和显示
<div id="Layer2" style="position: absolute;top:120px;left:40px;z-index:66;width:60%;visibility: hidden;">
</div>
js的写法
function show(indexid){
if (document.all["select3"].options[document.all["select3"].selectedIndex].value !="0" && document.all["select3"].options[document.all["select3"].selectedIndex].value !=" ") {
Layer2.style.visibility="visible";
}
else
{
Layer2.style.visibility="hidden";
}
}
7.一个简单的AJAX
<script type="text/javascript" src="<c:url value='/js/prototype.js'/>"></script>//引入AJAX的JS
//两个主要的方法
function checkHaveRemind(obj){
ClearList(smsForm.elements['roleId']);
var url = "<c:url value='/berheley/sms/formSendMessage.ao'/>";
var person = obj;
var pars = "method=searchSmsOfSwf&processId="+person;
//alert (pars);
var myAjax = new Ajax.Request(url,{method:'post',parameters:pars,onComplete:appendAnswer});
}
function appendAnswer(originalRequest)
{
//消息格式
//<tag>
//<swf><swfname></swfname>
//<swfid></swfid></swf>
//</tag>
var message=originalRequest.responseXml;
//var tag = message.getElementsByTagName("id").value;
//document.getElementById("test").innerHTML=message.getElementsByTagName("id")[0].childNodes[0].nodeValue;
//getElementById("test").innerHtml = "<font>用户已经存在。</font>";
//window.alert(tag);
var err = message.getElementsByTagName('error');
if(err!=null && err.length==1){
alert("获得节点信息失败,请与管理员联系!/r/n"+err[0].firstChild.nodeValue);
return;
}
if(info !=null && info.length==1){
for(var i = 0; i< message.getElementsByTagName("swf").length;i++){
var id= message.getElementsByTagName("swf")[i].childNodes[0].firstChild.nodeValue;
var name = message.getElementsByTagName("swf")[i].childNodes[1].firstChild.nodeValue;
smsForm.elements['roleId'].options[smsForm.elements['roleId'].options.length] = new Option(name, id);
}}else{
alert("系统异常,请与管理员联系!");
return;
}
}
7.XML文件的操作
取出其中的一个接点
Element rowDatas = (Element) document.selectSingleNode("//主节点/ROWDATA");
一个 CDATA 部件以"<![CDATA[" 标记开始,以"]]>"标记结束//在CDATA内部的所有内容都会被解析器忽略。
List list = document.selectNodes("/styles/style/@name" );//遍例属性NAME
Attribute attr=element.attribute("name"); //得到节点的属性"NAME"
attr.getValue()//得到属性值
element.getText()//得到节点的内容
使用dom4j的xPath解析XML
国外的dom4j已经很流行了,国内的相关资料相对较少,但普及风暴也即将到来。我们公司(老外开的)解析XML就是用的dom4j。
今天公司没事做,自己也写一个小例子贴上来,嘻~~
books.xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<!--This is a test for dom4j, jakoes, 2007.7.19-->
<book show="yes" url="lucene.net">
<title id="456">Lucene Studing</title>
</book>
<book show="yes" url="dom4j.com">
<title id="123">Dom4j Tutorials</title>
</book>
<book show="no" url="spring.org">
<title id="789">Spring in Action</title>
</book>
<owner>O'Reilly</owner>
</books>
下面我们使用dom4j的xPath来解析:
segment of ParseXML.java:
public void parseBooks(){
SAXReader reader = new SAXReader();
try {
Document doc = reader.read("books.xml");
Node root = doc.selectSingleNode("/books");
List list = root.selectNodes("book[@url='dom4j.com']");
for(Object o:list){
Element e = (Element) o;
String show=e.attributeValue("show");
System.out.println("show = " + show);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Document doc = reader.read("books.xml");的意思是加载XML文档,此是可以用doc.asXML()来查看,它将打印整个xml文档。
Node root = doc.selectSingleNode("/books");是读取刚才加载的xml文档内的books节点下的所有内容,对于本例也是整个xml文档。
当然我们也可以加载/books下的某一个节点,如:book节点
Node root = doc.selectSingleNode("/books/book");
或:Node root = doc.selectSingleNode("/books/*");
注意:如果有多个book节点,它只会读取第一个
root.asXML()将打印:
<book show="yes" url="lucene.net">
<title id="456">Lucene Studing</title>
</book>
既然加载了这么多,那我怎么精确的得到我想要的节点呢,别急,看下面:
List list = root.selectNodes("book[@url='dom4j.com']");
它的意思就是读取books节点下的book节点,且book的节点的url属性为dom4j.com
为什么使用list来接收呢,如果有两个book节点,且它们的url属性都为dom4j.com,此时就封闭到list里了。
如果想读取books下的所有book节点,可以这样:
List list = root.selectNodes("book");
如果想读取books节点下的book节点下的title节点,可以这样:
List list2 = root.selectNodes("book[@url='dom4j.com']/title[@id='123']");
注意:selectNodes()参数的格式:
节点名[@属性名='属性值'],如:book[@url='dom4j.com']
如果有多个节点,用“/”分开,如:book[@url='dom4j.com']/title[@id='123']
最近就是读取封闭在List里的内容了,可以用Node来读取,也可以用Element来转换。
attributeValue("属性")是读取该节点的属性值
getText()是读取节点的的内容。
List list = root.selectNodes("book[@url='dom4j.com']");//遍例所有@url='dom4j.com'的节点
for(Object o:list){
Element e = (Element) o;
String show=e.attributeValue("show");
System.out.println("show = " + show);
}
List list = document.selectNodes( "//foo/bar" );
for(int i=0;i<list.size();i++){
Element ee=(Element)list.get(i);
String name=ee.getName();
String value=ee.getText();
}
读取XML文件的内容
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlName);
doc.normalize();
NodeList info = doc.getElementsByTagName("formData");
Element datafilename = (Element)info.item(0);
String datafile_name = isNotNull(datafilename.getElementsByTagName("hd_datafilename").item(0).getFirstChild().getNodeValue());
Element edtno = (Element)info.item(0);
String edt_no = isNotNull(edtno.getElementsByTagName("edtReceiveNo").item(0).getFirstChild().getNodeValue());
Element ed_year = (Element)info.item(0);
String ed_yearcode = isNotNull(edtno.getElementsByTagName("ed_yearcode").item(0).getFirstChild().getNodeValue());
if (edt_no != null && !"".equals(edt_no)) {
saveNumber(datafile_name, edt_no,ed_yearcode);
} else {
;
}
写入一般的操作
File file = new File(rootPath+File.separator+"文件信息.XML");
try
{
XMLWriter writer = null;
OutputFormat format= OutputFormat.createPrettyPrint();
format.setEncoding("GB2312");
writer= new XMLWriter(new FileOutputStream(file),format);//用FileOutputStream 解决utf-8编码。
Document document = DocumentHelper.createDocument();
Element root = document.addElement("主节点");
Element fields= root.addElement("FIELDS");
fields.addElement("FIELD").addAttribute("FieldName","电子文档号").addAttribute("FieldType","String").addAttribute("WIDTH","32");
fields.addElement("FIELD").addAttribute("FieldName","全宗号").addAttribute("FieldType","String").addAttribute("WIDTH","5");
fields.addElement("FIELD").addAttribute("FieldName","数据格式").addAttribute("FieldType","String").addAttribute("WIDTH","40");
root.addElement("ROWDATA");
writer.write(document);
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
throw new Exception("文件级目录.XML 创建失败");
}