检查email地址的
function emailCheck (emailStr) {
emailStr = emailStr.toLowerCase();
var checkTLD=1;
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
}
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
}
}
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.");
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
}
}
if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The email address must end in a well-known domain or two letter " + "country.");
return false;
}
if (len<2) {
alert("This email address is missing a hostname!");
return false;
}
return true;
}
function emailCheck (emailStr) {
emailStr = emailStr.toLowerCase();
var checkTLD=1;
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
}
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
}
}
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.");
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
}
}
if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The email address must end in a well-known domain or two letter " + "country.");
return false;
}
if (len<2) {
alert("This email address is missing a hostname!");
return false;
}
return true;
}
解决方案 »
- struts2.1.8找不到类,怎么办
- 权限问题
- getWriter() has already been called for this response
- 请问如何用JSP 截取img标记?
- java 视频处理问题,跪求高手指点...
- 紧急求救,jsp页数据导出到EXCEL时要动态生成EXCEL文件名。
- error infomation:java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Date
- 求救! 用cewolf生成报表图片的问题,困扰了很多天,都没搞定 !!
- jsf问题
- jboss cmp2.0的问题,怎样使entitybean中的数据马上更新的数据库?另外,还有容器事务的问题?
- 请问有什么方法可以在栽入一个JSP页面的时候将scriptlet中ArrayList元素清空?
- statement.addBatch() /statement.executeBatch() 返回结果集?
function isInvalidDateScope(theDate,startDate,endDate,separator){
if (isInvalidDateScope.arguments.length==5)
theDoAlert=isInvalidDateScope.arguments[4]
else
theDoAlert=true
n_theDate=0
n_startDate=0
n_endDate=0
theDateUTC = Date.UTC (getDatePart(theDate,1,separator),
parseInt(getDatePart(theDate,2,separator),10)-1,
getDatePart(theDate,3,separator),
0,0,0
);
startUTC = Date.UTC (getDatePart(startDate,1,separator),
parseInt(getDatePart(startDate,2,separator),10)-1,
getDatePart(startDate,3,separator),
0,0,0
);
endUTC = Date.UTC (getDatePart(endDate,1,separator),
parseInt(getDatePart(endDate,2,separator),10)-1,
getDatePart(endDate,3,separator),
0,0,0
);
if (startUTC>endUTC){
if (theDoAlert)
alert("起始日期不能大于终止日期!")
return true
}
if (theDateUTC<startUTC || theDateUTC>endUTC)
return true
else
return false
}
请贴一下详细内容
<script language="javascript">
function sub()
{
if(document.form1.logname.value=="")
{
window.alert("请填写你的登录名!");
window.form1.logname.focus();
return false;
}
if(document.form1.realname.value=="")
{
window.alert("请填写你的真名!");
window.form1.realname.focus();
return false;
}
if(document.form1.passwd1.value=="")
{
window.alert("请填写密码!");
window.form1.passwd1.focus();
return false;
}
if(document.form1.passwd1.value!=document.form1.passwd2.value)
{
window.alert("请验证密码!");
window.form1.passwd2.focus();
return false;
}
if(document.form1.email.value=="")
{
window.alert("请填写你的E_mail!");
window.form1.email.focus();
return false;
}
document.form1.submit();
}
</script>
// * @(#)FileUtils.java
// * @version 1.0
// * @description 常用目录文件操作类
// * @author Filippo Guan
//*******************************************************************************//import java.io.*;public class FileUtils
{
public FileUtils()
{
} public static void copy(File src, File dest, boolean cover)
throws IOException
{
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
byte buf[] = new byte[1024];
int i;
try
{
while((i = fis.read(buf)) >= 0)
{
fos.write(buf, 0, i);
}
}
finally
{
try
{
fis.close();
}
catch(Exception exception1)
{
} try
{
fos.close();
}
catch(Exception exception2)
{
}
}
} public static void copy(String src, String dest, boolean cover) throws IOException
{
File fsrc = new File(src);
File fdest = new File(dest);
copy(fsrc,fdest,cover);
} public static void copytree(File src, File dest, boolean cover) throws IOException
{
if(src.isFile())
{
copy(src, dest, cover);
}
else
{
File children[] = src.listFiles();
for(int i = 0; i < children.length; i++)
{
File f = new File(dest, children[i].getName());
if(children[i].isDirectory())
{
f.mkdirs();
copytree(children[i], f, cover);
}
else
{
copy(children[i], f, cover);
}
}
}
} public static void copytree(String src, String dest, boolean cover) throws IOException
{
File fsrc = new File(src);
File fdest = new File(dest);
copytree(fsrc,fdest,cover);
} public static void movetree(File src, File dest, boolean cover) throws IOException
{
copytree(src, dest, cover);
deltree(src);
} public static void deltree(File f)
{
File children[] = f.listFiles();
if(children != null && children.length != 0)
{
for(int i = 0; i < children.length; i++)
{
deltree(children[i]);
}
}
f.delete();
} public static void deltree(String path)
{
File f = new File(path);
deltree(f);
} public static void move(String src, String dest, boolean cover) throws IOException
{
File fsrc = new File(src);
File fdest = new File(dest);
copy(fsrc,fdest,cover);
fsrc.delete();
} public static boolean find(File root, FileFilter filter)
{
if(filter.accept(root))
{
return true;
} File children[] = root.listFiles();
if(children == null || children.length == 0)
{
return false;
} for(int i = 0; i < children.length; i++)
{
if(find(children[i], filter))
{
return true;
}
} return false;
} public static boolean contains(File file, String suffix)
{
if(!file.exists() || !file.isDirectory())
{
return false;
}
File children[] = file.listFiles();
for(int i = 0; i < children.length; i++)
{
if(children[i].isFile() && children[i].getName().endsWith(suffix))
{
return true;
}
} return false;
} //读取单行文件内容
public static String getFline(String filePath)
{
String fc = null; try
{
BufferedReader f = new BufferedReader(new FileReader(filePath));
fc = f.readLine();
f.close();
}
catch (IOException e)
{
System.out.println("readLine problem, terminating.");
} return fc;
}
//to be continue...
public static String getIline(String filePath)
{
String fc = null; try
{
BufferedReader f = new BufferedReader(new FileReader(filePath));
fc = f.readLine();
long l = Long.parseLong(fc);
l++;
fc = String.valueOf(l);
f.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
bw.write(fc + "\n");
bw.flush();
bw.close();
}
catch (IOException e)
{
System.out.println("readLine problem, terminating.");
} return fc;
} public static String getFileExt(String fileName)
{
String ext = "";
int dot = fileName.lastIndexOf(".");
if (dot != -1)
{
ext = fileName.substring(dot + 1);
}
return ext;
} public static String getFullFileName(String filePath)
{
String fileName = filePath;
int i = filePath.lastIndexOf("/");
if (i != -1)
{
fileName = filePath.substring(i + 1);
}
return fileName;
} public static String getFileName(String filePath)
{
String fileName = filePath;
int i = filePath.lastIndexOf("/");
int j = filePath.lastIndexOf(".");
if (i != -1)
{
fileName = filePath.substring(i + 1, j);
}
return fileName;
} public static String getPath(String filePath)
{
String path = "";
int i = filePath.lastIndexOf("/");
if (i != -1)
{
path = filePath.substring(0,i);
}
return path;
} public static boolean WriteTo(String path, String info)
{
try
{
File f = new File(path);
PrintWriter out = new PrintWriter(new FileWriter(f));
out.print(info);
out.close();
return true;
}
catch (IOException e)
{
return false;
}
} //追加字符串
public static boolean Append(String path,String info)
{
try
{
File f = new File(path);
PrintWriter out;
FileWriter theFile;
if (f.exists())
{
theFile = new FileWriter(path,true);
out = new PrintWriter(theFile);
}
else
{
theFile = new FileWriter(f);
out = new PrintWriter(theFile);
}
out.print(info + "\n");
out.close();
theFile.close();
return true;
}
catch (IOException e)
{
return false;
}
} public static String getFileContent(File srcfile)
{
String strReturn = ""; try
{
BufferedInputStream buff = new BufferedInputStream(new FileInputStream(srcfile)); int in = 0;
do{
in = buff.read();
if(in != -1)
{
strReturn += (char)in;
}
}while(in != -1); return strReturn;
}
catch(Exception e)
{
return strReturn;
}
} public static String getFileContent(String fpath)
{
File srcfile = new File(fpath);
return getFileContent(srcfile);
} public static boolean isType(String ext,String ptype)
{
if (ext.equals("jpg")||ext.equals("jpeg")||ext.equals("gif")||ext.equals("png")||ext.equals("bmp"))
{
if(ptype.equals("pic"))
{
return true;
}
}
else if (ext.equals("mid")||ext.equals("amr")||ext.equals("wma"))
{
if(ptype.equals("ring"))
{
return true;
}
}
else if (ext.equals("htm")||ext.equals("html"))
{
if(ptype.equals("webpage"))
{
return true;
}
}
else if (ext.equals("css"))
{
if(ptype.equals("css"))
{
return true;
}
}
else if (ext.equals("htt")||ext.equals("ini")||ext.equals("inc"))
{
if(ptype.equals("htt"))
{
return true;
}
}
else if (ext.equals("js")||ext.equals("htc"))
{
if(ptype.equals("js"))
{
return true;
}
}
return false;
}
}
* Web applications.
*/public class urldeal { /** For use in URLs referenced by JSP pages or servlets, where
* you want to avoid hardcoding the Web app name. Replace
* <PRE><XMP>
* <IMG SRC="/images/foo.gif" ...>
* with the following two lines:
* <% String imageURL = webAppURL("/images/foo.gif",
* request); %>
* <IMG SRC="<%= imageURL %>"...>
*
* </XMP></PRE>
*/ public static String webAppURL(String origURL,
HttpServletRequest request) {
return(request.getContextPath() + origURL);
} /** For use when you want to support session tracking with
* URL encoding and you are putting a URL
* beginning with a slash into a page from a Web app.
*/ public static String encodeURL(String origURL,
HttpServletRequest request,
HttpServletResponse response) {
return(response.encodeURL(webAppURL(origURL, request)));
} /** For use when you want to support session tracking with
* URL encoding and you are using sendRedirect to send a URL
* beginning with a slash to the client.
*/ public static String encodeRedirectURL
(String origURL,
HttpServletRequest request,
HttpServletResponse response) {
return(response.encodeRedirectURL
(webAppURL(origURL, request)));
}
}
///把日期转换成汉字 cnDateFormat("2002/01/01","/") out 二零零二年一月一日 or cnDateFormat("2002-01-01","-") out 二零零二年一月一日
public String cnDateFormat(String sDate, String DelimeterChar) {
String restr = "";
String tmpArr[] = sDate.split(DelimeterChar);
String dArr[] = {
"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
for (int i = 0; i < 10; i++) {
Integer x = new Integer(i);
String temp = x.toString();
tmpArr[0] = tmpArr[0].replaceAll(temp, dArr[i]);
}
tmpArr[0] = tmpArr[0] + "年";
if (tmpArr[1].length() == 1) {
tmpArr[1] = dArr[Integer.parseInt(tmpArr[1])] + "月";
}
else {
if (tmpArr[1].substring(0, 1).equals("0")) {
tmpArr[1] = dArr[Integer.parseInt(tmpArr[1].substring(tmpArr[1].length() -
1, tmpArr[1].length()))] + "月";
}
else {
tmpArr[1] = "十" +
dArr[Integer.parseInt(tmpArr[1].substring(tmpArr[1].length() - 1,
tmpArr[1].length()))] + "月";
tmpArr[1] = tmpArr[1].replaceAll("零", "");
} }
if (tmpArr[2].length() == 1) {
tmpArr[2] = dArr[Integer.parseInt(tmpArr[2])] + "日";
}
else {
if (tmpArr[2].substring(0, 1).equals("0")) {
tmpArr[2] = dArr[Integer.parseInt(tmpArr[2].substring(tmpArr[2].length() -
1, tmpArr[2].length()))] + "日";
}
else {
tmpArr[2] = dArr[Integer.parseInt(tmpArr[2].substring(0, 1))] + "十" +
dArr[Integer.parseInt(tmpArr[2].substring(tmpArr[2].length() - 1,
tmpArr[2].length()))] + "日";
tmpArr[2] = tmpArr[2].replaceAll("零", "");
}
}
return tmpArr[0] + tmpArr[1] + tmpArr[2];
}
1.比较日期
public static boolean compareDate( String date1 ,String date2 ) {
if ( date1 == null || date2 == null ) {
System.out.println("参数不能为空") ;
return false ;
}
String str = date1.substring(0,4) + date1.substring(5,7) + date1.substring(8,10) ;
int date2Int1 = Integer.parseInt(str) ;
str = date2.substring(0,4) + date2.substring(5,7) + date2.substring(8,10) ;
int date2Int2 = Integer.parseInt(str) ;
return date2Int1 > date2Int2 ;
}
date1.compareTo(date2);
如果返回0,说明两个日期相等
如果返回大于0,说明date1在date2之后
如果返回小于0,说明date1在date2之前SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:ss");
Date d1=null,d2=null;
try {
d1 = sdf.parse("2004-03-09 11:12");
d2 = sdf.parse("2004-06-10 01:02");
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
d1.compareTo(d2);
2.拆分字符串:
public static String[] split(String s, String separator)
{
if(s == null)
throw new NullPointerException("source String cannot be null");
if(separator == null)
throw new NullPointerException("separator cannot be null");
if(separator.length() == 0)
throw new IllegalArgumentException("separator cannot be empty"); ArrayList buffer = new ArrayList();
int start = 0;
int end = s.indexOf(separator);
while(end != -1)
{
buffer.add(s.substring(start, end));
start = end + separator.length();
end = s.indexOf(separator, start);
}
buffer.add(s.substring(start, s.length())); return (String[]) buffer.toArray(new String[0]);
}
用法:
String[] result = split("a,b,c,d,e", ",");
3.产生zip文件的程序:public void makeZIP(String s_zipPath,
String s_newZipFile,
String s_fileName,
String s_filePath,
String status,
String yearmonth)
throws FileNotFoundException,IOException
{
try
{
File f_compressFile=new File(s_filePath,s_fileName);
if (f_compressFile.isFile())
{
FileInputStream s_fileIn=new FileInputStream(f_compressFile);
DataInputStream in = new DataInputStream(s_fileIn);
outZip.putNextEntry(new ZipEntry(s_fileName)); int c;
while((c = in.read()) != -1)
outZip.write(c);
in.close();
s_fileIn.close();
outZip.closeEntry();
java.io.File ZipfileDir = new java.io.File(s_filePath+"\\"+s_fileName);
if (ZipfileDir.exists())
{
ZipfileDir.delete();
}
if (status=="end")
{
outZip.close(); this.addNormalMessage("Download/"+
this.getSessionParam().getString(
CMN_APP_ColConstant.MANNO)+"_"+yearmonth+".zip"); }
}
else if (f_compressFile.isDirectory())
{
File f_zip=new File(s_zipPath,s_newZipFile);
FileOutputStream f_zipFile = new FileOutputStream(f_zip);
outZip = new ZipOutputStream(new DataOutputStream(f_zipFile));
String[] s_fileList=f_compressFile.list();
String s_newDirectory=f_compressFile.getAbsolutePath();
String nowStatus=null;
for (int i=0;i<s_fileList.length ;i++ )
{
if (i==s_fileList.length-1)
{
nowStatus="end";
}
makeZIP(s_zipPath,s_newZipFile,s_fileList[i],
s_newDirectory,nowStatus,yearmonth);
}
}
//
}
catch (Exception e)
{
e.printStackTrace();
}
}
1.新建目录<%@ page contentType="text/html;charset=gb2312"%>
<%
String filePath="c:/aaa/";
filePath=filePath.toString();//中文转换
java.io.File myFilePath=new java.io.File(filePath);
if(!myFilePath.exists())
myFilePath.mkdir();
%> 2。新建文件<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%
String filePath="c:/哈哈.txt";
filePath=filePath.toString();
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile=new FileWriter(myFilePath);
PrintWriter myFile=new PrintWriter(resultFile);
String strContent = "中文测试".toString();
myFile.println(strContent);
resultFile.close();
%> 3。删除文件<%@ page contentType="text/html;charset=gb2312"%>
<%
String filePath="c:/支出证明单.xls";
filePath=filePath.toString();
java.io.File myDelFile=new java.io.File(filePath);
myDelFile.delete();
%> 4。文件拷贝<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
int bytesum=0;
int byteread=0;
file://读到流中
InputStream inStream=new FileInputStream("c:/aaa.doc");
FileOutputStream fs=new FileOutputStream( "d:/aaa.doc");byte[] buffer =new byte[1444];
int length;
while ((byteread=inStream.read(buffer))!=-1)
{
out.println("<DT><B>"+byteread+"</B></DT>");
bytesum+=byteread;
System.out.println(bytesum);
fs.write(buffer,0,byteread);
}
inStream.close();
%> 5。整个文件夹拷贝<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%String url1="C:/aaa";
String url2="d:/java/";
(new File(url2)).mkdirs();
File[] file=(new File(url1)).listFiles();
for(int i=0;i<file.length;i++){
if(file[i].isFile()){
file[i].toString();
FileInputStream input=new FileInputStream(file[i]);
FileOutputStream output=new FileOutputStream(url2+"/"+(file[i].getName()).toString());
byte[] b=new byte[1024*5];
int len;
while((len=input.read(b))!=-1){
output.write(b,0,len);
}
output.flush();
output.close();
input.close();
}
}
%> 6。文件下载<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
String fileName = "zsc104.swf".toString();
//读到流中
InputStream inStream=new FileInputStream("c:/zsc104.swf");
//设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len;
while((len=inStream.read(b)) >0)
response.getOutputStream().write(b,0,len);
inStream.close();
%> 7。数据库字段中的文件下载<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="DBstep.iDBManager2000.*"%>
<%
int bytesum=0;
int byteread=0;
//打开数据库
ResultSet result=null;
String Sql=null;
PreparedStatement prestmt=null;
DBstep.iDBManager2000 DbaObj=new DBstep.iDBManager2000();
DbaObj.OpenConnection();
//取得数据库中的数据
Sql="select * from t_local_zhongzhuan ";
result=DbaObj.ExecuteQuery(Sql);
result.next();file://将数据库中的数据读到流中
InputStream inStream=result.getBinaryStream("content");
FileOutputStream fs=new FileOutputStream( "c:/dffdsafd.doc");byte[] buffer =new byte[1444];
int length;
while ((byteread=inStream.read(buffer))!=-1)
{
out.println("<DT><B>"+byteread+"</B></DT>");
bytesum+=byteread;
System.out.println(bytesum);
fs.write(buffer,0,byteread);
}
%> 8。把网页保存成文件<%@ page import="java.text.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%
URL stdURL = null;
BufferedReader stdIn = null;
PrintWriter stdOut = null;
try {
stdURL = new URL("http://www.163.com");
}
catch (MalformedURLException e) {
throw e;
}try {
stdIn = new BufferedReader(new InputStreamReader(stdURL.openStream()));
stdOut = new PrintWriter(new BufferedWriter(new FileWriter("c:/163.html")));
}
catch (IOException e) {
} /***把URL指定的页面以流的形式读出,写成指定的文件***/
try {
String strHtml = "";
while((strHtml = stdIn.readLine())!=null) {
stdOut.println(strHtml);
}
}
catch (IOException e) {
throw e;
}
finally {
try {
if(stdIn != null)
stdIn.close();
if(stdOut != null)
stdOut.close();
}
catch (Exception e) {
System.out.println(e);
}
}
%> 9。直接下载网上的文件<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%
int bytesum=0;
int byteread=0;URL url = new URL("http://pimg.163.com/sms/micheal/logo.gif");
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs=new FileOutputStream( "c:/abc.gif"); byte[] buffer =new byte[1444];
int length;
while ((byteread=inStream.read(buffer))!=-1)
{
out.println("<DT><B>"+byteread+"</B></DT>");
bytesum+=byteread;
System.out.println(bytesum);
fs.write(buffer,0,byteread);
}
%>
/*
目录递归并删除该目录下所以的文件及文件夹
*/
public void SearchDirOk(String Dir){
File tempFolder = new File(Dir);
String fileList[] =tempFolder.list();
for (int i = 0;i < fileList.length;i++){
File tempSubFolder = new File(Dir+"/"+fileList[i]);
if (tempSubFolder.isDirectory())
this.SearchDirOk(Dir+"/"+fileList[i]);
else
tempSubFolder.delete();
}
tempFolder.delete();
}调用方法:
CommonClass common = new CommonClass();
common.SearchDirOk((String)sessionDir.toString()) ;
sessionDir为路径删除文件:
public static void delete(String filename) {
File f = new File(filename); if (!f.exists()) fail("Delete: no such file or directory: " +filename);
if (!f.canWrite()) fail("Delete: write protected: " + filename); if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
fail("Delete: directory not empty: " + filename);
} boolean success = f.delete();
if (!success) fail("Delete: deletion failed");
}
protected static void fail(String msg) throws IllegalArgumentException {
throw new IllegalArgumentException(msg);
}下面是两种删除方法:
方法1:
try {
String sql1 = "drop table DATA ";
int num1 = stmt.executeUpdate(sql1);
String sql2 = "drop table HEAD ";
int num2 = stmt.executeUpdate(sql2);
String sql3 = "drop table payinfo ";
int num3 = stmt.executeUpdate(sql3);
} catch (Exception ex) {
SystemLog.writeErrorLog("删除数据库文件出错!", ex.toString());
}方法2:
File f = new File(path);
File[] fname = f.listFiles();
try{
for(int i=0;i<fname.length;i++){
fname[i].delete();
}
}catch (Exception e) {
SystemLog.writeErrorLog("删除BDF数据库文件出错!!"+e.getMessage(), e.toString());
}
获取某月的天数.
public static int getDayCountOfMonth(int year,int month){
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DATE,0);
return calendar.get(Calendar.DATE);
}
呵,漏了一个...
/*
* 删除一个目录下的所有文件
*/
public static void delAllFile(String path) {
File file = new File(path);
if(!file.exists()) return;
if(!file.isDirectory()) return;
String[] tempList = file.list();
File temp = null;
for(int i = 0; i < tempList.length; i++) {
if(path.endsWith(File.separator))
temp = new File(path + tempList[i]);
else
temp = new File(path + File.separator + tempList[i]);
if(temp.isFile()) temp.delete();
if(temp.isDirectory()) delAllFile(path + tempList[i]);
}
}
统计在线的..
6.在session中加入监听类,类的示例代码如下:
onLineUser.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
public class onLineUser implements HttpSessionBindingListener {
public onLineUser(){
}
private Vector users=new Vector();
public int getCount(){
users.trimToSize();
return users.capacity();
}
public boolean existUser(String userName){
users.trimToSize();
boolean existUser=false;
for (int i=0;i<users.capacity();i++ )
{
if (userName.equals((String)users.get(i)))
{
existUser=true;
break;
}
}
return existUser;
}
public boolean deleteUser(String userName) {
users.trimToSize();
if(existUser(userName)){
int currUserIndex=-1;
for(int i=0;i<users.capacity();i++){
if(userName.equals((String)users.get(i))){
currUserIndex=i;
break;
}
}
if (currUserIndex!=-1){
users.remove(currUserIndex);
users.trimToSize();
return true;
}
}
return false;
}
public Vector getOnLineUser()
{
return users;
}
public void valueBound(HttpSessionBindingEvent e) {
users.trimToSize();
if(!existUser(e.getName())){
users.add(e.getName());
System.out.print(e.getName()+"\t 登入到系统\t"+(new Date()));
System.out.println(" 在线用户数为:"+getCount());
}else
System.out.println(e.getName()+"已经存在");
}
public void valueUnbound(HttpSessionBindingEvent e) {
users.trimToSize();
String userName=e.getName();
deleteUser(userName);
System.out.print(userName+"\t 退出系统\t"+(new Date()));
System.out.println(" 在线用户数为:"+getCount());
}
}
jsp:
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="onlineuser" class="temp.jb.onLineUser" scope="application"/>
<html>
<head>
</head>
<body onUnload="postMessage()">
<center>
<p><h1>登陆成功,欢迎访问</h1></p>
</center>
<% session = request.getSession(false); %>
<%
String username=request.getParameter("username");
if (onlineuser.existUser(username)){
out.println("用户<font color=red>"+username+"</font>已经登陆!");
}else{
session.setMaxInactiveInterval(50); //Sesion有效时长,以秒为单位
session.setAttribute(username,onlineuser);
out.println("欢迎新用户:<font color=red>"+username+"</font>登陆到系统!");
}
out.println("<br>当前在线用户人数:<font color=red>"+onlineuser.getCount()+"</font><br>");
String ip = request.getRemoteAddr();
out.println("<br>IP:<font color=red>"+ip+"</font><br>");
Vector vt=onlineuser.getOnLineUser();
Enumeration e = vt.elements();
out.println("在线用户列表");
out.println("<table border=1>");
out.println("<tr><td>用户名</td></tr>");
while(e.hasMoreElements()){
out.println("<tr><td>");
out.println((String)e.nextElement()+"<br>");
out.println("</td></tr>");
}
out.println("</table>");
%>
<center>
<p> </p>
[<a href="javascript:window.close()">关闭窗口</a>]
<%
out.println("<p><a href='logout.jsp?username="+username+"'>退出系统</a></p>");
%>
</center>
<Script>
function postMessage(){
<%onlineuser.deleteUser(request.getParameter("username"));%>
}
</Script>
</body>
</html>
的贴子很不错,有一个我正要的用的功能
谢谢你,谢谢bluesky35(蓝天) ( )
谢谢allpeople
package database;import usua.*;
import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;public class DBFileBean extends DButil{
public static String rootPath = null;
public static String thisPath = null;
//public static String destPath = null;
public static LinkedList ourSet = typeSet.getOurSet();
public DBFileBean(javax.servlet.http.HttpServletRequest request)
throws SQLException,NamingException{
rootPath=request.getSession().getServletContext().getRealPath("");
//rootPath = rootPath.toString().concat("/sohosite");
}
public static String getRootPath() { return rootPath; }
public String getSavePath(){
return thisPath;
}
public boolean setSavePath(String str){
String applyDate = usuallyUse.getSpDate(str);
boolean pass;
//save step1: create dir as: /data/20040404/
thisPath = "data/"+applyDate;
pass = this.createDir(thisPath);
return pass;
}
/*
@Function: Check file name whether accord our seted!
@param: file name String.
@returnValue: return the path of this file save path.!
*/
public String saveSpecialFile(String fileName) throws NamingException,
java.sql.SQLException,ServletException {
String savePath = null, tempRoot = null,
type = "", soureType = "", batch = "";
boolean pass = true;
//gained the date type set from database.
TreeMap typeMap = DBuse.getTypeSet();
//validate file Name.
TreeMap fileNameMap;
fileNameMap = checkFileName(fileName);
if (fileNameMap.size()!=0)
{
type = ((String) fileNameMap.get("type")).toUpperCase();
soureType = type;
}
else {
return savePath;
}
if (!typeMap.containsKey(type) && !ourSet.contains(type)) {
return savePath;
}
tempRoot = getSavePath();
batch = (String) fileNameMap.get("batch");
savePath = tempRoot + "/" + soureType + "/" + batch;
pass = this.createDir(savePath);
if (!pass) return null;
return savePath;
}
@Function: check File Name
@param: file name string
my BUG: this class can't validate contained only one "\" String.
@returnValue:
a tree Map key as following..
no ------ member NO.
send ------ the sended Date
type ------ such as OKADA or KOHO..
batch ----- 1st 2nd 3rd 4th...
disgree ---- 13
tier ----- 3
exs ------- ZIP RAR EPS...
*/
public static TreeMap checkFileName(String fileName) throws java.sql.SQLException,
NamingException {
String originalName,nameHead,no,sendHead,send,
type,endStr,tier,exs;
String invalid = "[]{}!@#$%^&*-+=~`/:;\'\"<>,";
originalName = fileName;
int i = 0, k = 0, counter = 0;
boolean pass = true;
DBuse us = new DBuse();
TreeMap typeMap = us.getTypeSet();
fileName = fileName.toLowerCase();
List fileNameList = new ArrayList();
TreeMap destMap = new TreeMap();
for (int j=0; j<fileName.length(); j++) {
String ss = String.valueOf(fileName.charAt(j));
if (invalid.indexOf(ss) != -1 || invalid.indexOf("\\") != -1) {
pass = false;
break;
} else if(ss.equals(")") || ss.equals("(")) {
counter++;
}
}
if (counter>4) pass = false;
if (//!fileName.startsWith("(no")
fileName.endsWith(")")
|| !pass){
return destMap;
}
fileName = fileName.replaceAll("[(]","");
/*
@following file name is a example.
FileName: (no.10)0302okada_1st_13_(3).zip
fileNameList: [no.10)0302okada, 1st, 13, 3).zip]
CODE:
String[] partName = new String[st.countTokens()];
if (partName.length != 4)
return destMap;
*/
StringTokenizer st = new StringTokenizer(fileName,"_");
while (st.hasMoreTokens())
fileNameList.add(st.nextToken());
if (fileNameList.size() != 4) return destMap;
int sz = fileNameList.size();
/*
@no string.
nameHead: [no.10)0302okada
no: 10
*/
nameHead = (String) fileNameList.get(0);
no = nameHead.substring(nameHead.indexOf(".")+1,nameHead.lastIndexOf(")"));
for(int j=0; j<no.length(); j++)
{
String o = String.valueOf(no.charAt(j));
if(o.matches("[\\D]")){
destMap.clear();
return destMap;
}
}
destMap.put("no",no);
/*
@send string.
sendHead: 0302okada
i: 4 ^
send: 0302
*/
sendHead = nameHead.substring(nameHead.lastIndexOf(")")+1,nameHead.length());
for (i=0; isendHead.length(); i++)
{
String s = String.valueOf(sendHead.charAt(i));
if (s.matches("[a-zA-Z]")) break;
}
destMap.put("send",sendHead.substring(0,i));
/*
@type string.
sendHead: 0302okada
type: okada
*/
type = sendHead.substring(i,sendHead.length());
//if (ourSet.contains(type.toUpperCase()))
// type = (String) ourSet.getLast();
destMap.put("type",type);
/*
@batch string.
FileName: (no.10)0302okada_1st_13_(3).zip
batch: 1st ^^^
*/
destMap.put("batch",fileNameList.get(1));
/*
@digree String.
FileName: (no.10)0302okada_1st_13_(3).zip
digree: 13 ^^
*/
destMap.put("degree",fileNameList.get(sz-2));
/*
@Tier string.
FileName: (no.10)0302okada_1st_13_(3).zip
tier: 3 ^
*/
endStr = fileNameList.get(sz-1).toString();
tier = endStr.substring(0,endStr.lastIndexOf(")"));
destMap.put("tier",tier);
/*
@file extension name string.
exs: zip
*/
exs = endStr.substring(endStr.lastIndexOf(")")+2,endStr.length());
destMap.put("exs",exs);
destMap.put("name",originalName);
return destMap;
}
/*
@Function: create the special directory
@param: destination directory.
@returnValue: return true if create success!
*/
public boolean createDir(String dir){
boolean isSuccess = true;
dir = dir.toString();
if (dir==null) return false;
rootPath = getRootPath();
java.io.File file = new java.io.File(rootPath,dir);
//System.out.println("dir: "+ dir +"exis: "+file.exists());
if (!file.exists()) isSuccess = file.mkdirs();
return isSuccess;
}
/*
@Function: check the specail directory included given file??
@param: destination directory and file Name.
@returnValue: return a String only file exists.
*/
public String checkExists(String givePath,String FileName) throws IOException {
//System.out.println("invoke!!"+givePath);
rootPath = this.getRootPath();
String destPath = null;
if (givePath == null
|| FileName == null
|| givePath.trim().equals("")) {
return destPath;
}
java.io.File file = new java.io.File(rootPath, givePath);
if(!file.exists()) {
System.out.println("not exists!");
return null;
}
if(!file.isDirectory()) {
System.out.println("not dir!");
return null;
}
String[] pathList = file.list() ;
for (int i=0; i<pathList.length&&destPath == null; i++){
java.io.File pathFile = new java.io.File(rootPath, givePath + java.io.File.separator + pathList[i]);
if (pathFile.isFile() && pathFile.getName().equalsIgnoreCase(FileName) ){
destPath = (pathFile.getAbsolutePath()).toString();
//System.out.println("OK!");
return destPath;
//break;
} if (pathFile.isDirectory()){
destPath = checkExists(givePath + java.io.File.separator + pathList[i], FileName);
}
}
return destPath;
}
/*
@Function : Delete the special File
@param: file directory.
@returnValue: return true if delete success!
Author: du.zero 2004-02-25
*/
public boolean delFile(String dir){
boolean isSuccess = true;
//dir = dir.toString().toUpperCase();
if (dir==null) return false;
java.io.File file = new java.io.File(rootPath,dir);
if (file.exists()) isSuccess = file.delete();
//System.out.print("delete success,this is dir: "+dir);
return isSuccess;
} }
2.1 短时间,形如 (13:04:06)
function isTime(str)
{
var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
if (a == null) {alert('输入的参数不是时间格式'); return false;}
if (a[1]>24 || a[3]>60 || a[4]>60)
{
alert("时间格式不对");
return false
}
return true;
} 2.2 短日期,形如 (2003-12-05)
function strDateTime(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
} 2.3 长时间,形如 (2003-12-05 13:04:06)
function strDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null)return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
} 2.4 只有年和月。形如(2003-05,或者2003-5) 2.5 只有小时和分钟,形如(12:03)
3、表单类
3.1 所有的表单的值都不能为空
<input onblur="if(this.value.replace(/^\s+|\s+$/g,'')=='')alert('不能为空!')"> 3.2 多行文本框的值不能为空。
3.3 多行文本框的值不能超过sMaxStrleng
//检验文本框中内容是否超长
function CheckTextareaLength(val, max_length) {
var str_area=document.forms[0].elements[val].value;
if (str_area!=null&&str_area.length > max_length)
{
alert("字段文字超长,最多可输入" + max_length +"个字符,请重新输入!");
document.forms[0].elements[val].focus();
document.forms[0].elements[val].select();
return false;
}
return true;
}
3.4 多行文本框的值不能少于sMixStrleng
3.5 判断单选框是否选择。function CheckRadio(val,msg1,msg2)
{
var is_radio=document.forms[0].elements[val];
var s_msg1=(msg1==null || msg1=="")? "请选择 radio!":msg1;
var s_msg2=(msg2==null || msg2=="")? "没有可选的 radio!":msg2; if(is_radio)
{
if (document.forms[0].elements[val].value != null)
{
if (document.forms[0].elements[val].checked)
{
return true;
}
else
{
alert(s_msg1);
return false;
}
}
else
{
var check_length = document.forms[0].elements[val].length;
var i_count=0
for(var i=0;i<check_length;i++)
{
if (document.forms[0].elements[val](i).checked)
{
i_count=i_count+1;
return true;
}
}
if(i_count==0)
{
alert(s_msg1);
return false;
}
}
}//
else
{
alert(s_msg2);
return false;
}}
/**
*一个静态方法,返回一个数据库的连接。
*这样达到了对数据库连接统一控制的目的。
*/
public static Connection getConnection() {
Connection con=null;
try {
Context ctx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("java:comp/env/jdbc/master");
con = ds.getConnection();
}
catch(Exception e){
e.printStackTrace();
}
return con;
/*Connection con=null;
String CLASSFORNAME=("org.gjt.mm.mysql.Driver");
String SERVANDDB=("jdbc:mysql://localhost:3306/test");
String USER="root";
String PWD="";
try {
Class.forName(CLASSFORNAME);
con = DriverManager.getConnection(SERVANDDB,USER,PWD);
}
catch(Exception e){
e.printStackTrace();
}
return con;*/
}/**
* <pre>
* 调用方法示例:
* out.println("当前用户数量 " + SessionListener.getSessionCount() + "<br>");
* out.println("当前登录用户数量 " + SessionListener.getLoginSessionCount());
* SessionListener.getSessionUser().put(session.getId(),"张三");
* </pre>
*/
public class SessionListener implements HttpSessionListener {
private static Hashtable htSessionUser = new Hashtable();
/**
* 构造函数
*/
public SessionListener() {
}
/**
* @param se - HttpSessionEvent
*/
public void sessionCreated(HttpSessionEvent se) {
htSessionUser.put(se.getSession().getId(),"");
}
/**
* @param se - HttpSessionEvent
*/
public void sessionDestroyed(HttpSessionEvent se) {
htSessionUser.remove(se.getSession().getId());
}
/**
* @return Hashtable,该Hashtable的KEY含有所有会话的ID,如果该用户登录,则VALUE含有该用户的id。
*/
public static Hashtable getSessionUser() {
return htSessionUser;
}
/**
* @return int,访问当前站点的会话数。
*/
public static int getSessionCount() {
return htSessionUser.size();
}
/**
* @return int,访问当前站点的登录会话数。
*/
public static int getLoginSessionCount() {
Enumeration em = htSessionUser.elements();
int i = 0;
while(em.hasMoreElements()) {
String sValue = (String)em.nextElement();
if(!sValue.equals("")) i++;
}
return i;
}
}
贴出来大家看一看import java.io.*;
import javax.servlet.*;
import java.util.*;public class LifeCycle extends GenericServlet { FileOutputStream myNote = null;
PrintWriter myOut = null; public LifeCycle() {
try {
myNote = new FileOutputStream("C:\\myNote.txt");
myOut = new PrintWriter(myNote);
myOut.println(
"构造实例方法 LifeCycle 的调用时间:" + new Date() + System.currentTimeMillis());
Thread.sleep(1000);
myOut.flush();
} catch (Exception e) {
}
} public void init() {
try {
myOut.println(
"初始化方法 init 的调用时间:" + new Date() + System.currentTimeMillis());
Thread.sleep(1000);
myOut.flush();
} catch (Exception e) {
}
} public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
try {
myOut.println(
"服务方法 service 的调用时间:" + new Date() + System.currentTimeMillis());
Thread.sleep(1000);
myOut.flush();
} catch (Exception e) {
}
res.getWriter().print("Test");
} public void destroy() {
try {
myOut.println(
"释放方法 destroy 的调用时间:" + new Date() + System.currentTimeMillis());
Thread.sleep(1000);
myOut.flush();
myOut.close();
} catch (Exception e) {
}
}