| |||||||||
日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
---|---|---|---|---|---|---|---|---|---|
22 | 23 | 24 | 25 | 26 | 27 | 28 | |||
1 | 2 | 3 | 4 | 5 | 6 | 7 | |||
8 | 9 | 10 | 11 | 12 | 13 | 14 | |||
15 | 16 | 17 | 18 | 19 | 20 | 21 | |||
22 | 23 | 24 | 25 | 26 | 27 | 28 | |||
29 | 30 | 31 | 1 | 2 | 3 | 4 |
引用
蔣委員長 的 如何將class打包exe文件
class文件打包exe文件要經(jīng)過兩個(gè)步驟:
第一步:將class文件打包成jar文件,請(qǐng)參見我的上一篇文章:http://maidini.blog.163.com/blog/static/37762704200848910573/
第二步:將jar文件打包成exe文件。這是今天的重點(diǎn)
將jar打包exe 有許多工具,我以exe4j為例詳解打包過程:
第一步:下載exe4j,最新版本為4.1 如下圖 exe4j的官方網(wǎng)站
第二步:運(yùn)行exe4j.exe 我使用的是免安裝版(zip) 如下圖
第三步:運(yùn)行軟件exe4j,然后點(diǎn)擊Next
第四步:選擇第二項(xiàng)"JAR in EXE mode",然后點(diǎn)擊Next
第五步:在General中填入名稱,在Directories填入生成exe的目錄位置。如下圖:我將生成exe目錄設(shè)置為C:\ok ,然后點(diǎn)Next
第六步:Executable name處填入生成exe文件的名稱,Icon File處填寫圖標(biāo)文件位置,再點(diǎn)Next
第七步:首先設(shè)置Class Path的位置,即jar文件的位置。然后點(diǎn)OK
第八步:接著設(shè)置Main-Class 的位置,即main方法所在的位置。然后點(diǎn)OK 如下圖
設(shè)置完成后,如下圖: 一定要先設(shè)置Class Path,再設(shè)置Main class
第九步:填寫版本號(hào),最好不要填寫第二項(xiàng)。否則可能造成錯(cuò)誤(見后面),最后點(diǎn)擊Finish即可
錯(cuò)誤內(nèi)容:No JVM could be found on your system. Please define EXE4J_JAVA_HOME to point to an installed JDK or JRE or download a JRE from www.java.com
當(dāng)時(shí)出現(xiàn)這個(gè)錯(cuò)誤,查看了JDK和JRE都沒有問題,exe4j也是最新版。后來才發(fā)現(xiàn)是設(shè)置"Maximum version"。如果不填寫"Maximum version",就不報(bào)錯(cuò)。也不知道是不是exe4j的BUG
第十步:完成所有設(shè)置,點(diǎn)擊“Click Here to Start the Application”可以運(yùn)行測(cè)試生成的EXE文件
生成的最終的EXE程序,雙擊直接運(yùn)行?,F(xiàn)在可以把自己寫的小程序發(fā)給朋友們玩玩啦,呵呵
引用
蔣委員長 的 如何將Class打包Jar文件--Eclipse
開發(fā)環(huán)境:Eclipse + Win XP SP2
使用插件:Fatjar、Jigloo
閑話少說,直接切入正題。首先打開Eclipse,創(chuàng)建一個(gè)Java工程。如下圖:我機(jī)子上的是JDK1.6
第二步:用Jigloo插件創(chuàng)建一個(gè)窗體,為了更明顯演示我將窗體名字修改為“這是一個(gè)測(cè)試程序”。如下圖:
第三步:現(xiàn)在就該將運(yùn)行正常的java程序打包成jar文件。我使用Fatjar插件打包相當(dāng)方便、傻瓜。直接右鍵選擇要打包的工程,彈出的菜單中選擇“Build Fat Jar”。如下圖:
第四步:彈出對(duì)話框,需要將引導(dǎo)路徑修改,其他選項(xiàng)使用默認(rèn)設(shè)置,然后點(diǎn)擊Finish。“Main-Class”這項(xiàng)修改為Main方法所在的文件。此步不可缺少,否則打包的Jar文件雙擊不可運(yùn)行。
稍等一下,就打包成功如下圖:出現(xiàn)一個(gè)testexe_fat.jar文件。
進(jìn)入工程所在的目錄也可以看到一個(gè)testexe_fat.jar文件,雙擊它,就運(yùn)行了。如果無誤應(yīng)該彈出像圖2的界面。如下圖:
選擇jar文件右鍵,點(diǎn)擊open。相當(dāng)于雙擊jar文件如下圖:
總結(jié):打包Jar文件是將分散Class文件統(tǒng)一封裝的好辦法。雙擊運(yùn)行速度與沒打包前運(yùn)行速度沒有區(qū)別。打包一定要設(shè)置好Main-Class的路徑,否則JVM找不到入口程序。
如果不知道如何在Eclipse中安裝插件,請(qǐng)參見我的另一篇文章:http://maidini.blog.163.com/blog/static/37762704200832671334860/
引用
蔣委員長 的 Eclipse的插件安裝
眾所周知,Eclipse無法方便快速的開發(fā)Swing程序。因?yàn)镋clipse沒有自帶圖形化編碼窗口,如果要開發(fā)圖形化程序,只有手動(dòng)敲代碼非常不方便?,F(xiàn)在有一個(gè)插件Jigloo提供圖形化程序開發(fā)窗口,可以即拖即顯。如何將它安裝到Eclipse當(dāng)中呢?
安裝插件一般使用Link方式:Link意味鏈接,Eclipse加載時(shí)通過鏈接找到安裝的插件
如上圖所示:我的Eclipse路徑C:\Program Files\Eclipse 然后將Jigloo解壓到Eclipse安裝目錄中。這里需要注意Jigloo目錄下必須要有個(gè)叫Eclipse的目錄,Eclipse的目錄下才是放入features和plugins目錄。以上圖為例:C:\Program Files\Eclipse\Jigloo\Eclipse 路徑里放入features和plugins目錄,即features目錄路徑為:C:\Program Files\Eclipse\Jigloo\Eclipse\features,plugins目錄路徑為:C:\Program Files\Eclipse\Jigloo\Eclipse\plugins 這里必須要強(qiáng)調(diào)目錄路徑,因?yàn)槲沂褂玫氖荓ink方式安裝插件。插件安裝位置正確后,就該鏈接了(Link)。在Eclipse路徑C:\Program Files\Eclipse下建立一個(gè)links目錄(必須這個(gè)名字),并在links目錄下建立一個(gè)Jigloo.link的文件(文件名必須同插件目錄名相同,后綴名必須是link)。最后用記事本打開Jigloo.link文件,填入path = Jigloo(path = 插件目錄名)。保存后,重新啟動(dòng)Eclipse。如下圖
在新建項(xiàng)目中出現(xiàn)了一個(gè)叫GUI Forms的項(xiàng)目,說明插件安裝成功,這就是Jigloo插件提供的圖形化開發(fā)工具。寫在最后:
向大家推薦一個(gè)插件Aptana,這個(gè)插件可以調(diào)試Javascript代碼和HTML代碼。此插件還是第一款支持ajax調(diào)試的程序。詳見http://www.aptana.com/ 插件下載地址http://update.aptana.com/install/studio/3.2/
因?yàn)樾掳姹疽召M(fèi)(只有一個(gè)月免費(fèi)試用),我使用的老版本,安裝到Eclipse中有3個(gè)按鈕(如上圖,黃色驚嘆號(hào)和紅色叉)
如題,廢話不多說。
JSP頁面
hello.jsp
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>AJAX提交頁面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
function doso(){
var url = "actAction.do";
var s="武曉強(qiáng)斯蒂芬34-*(&_(*!$^_*!&#!^$+!*#&&";
s=encodeURIComponent(s); //轉(zhuǎn)換特殊字符
var parameter ="name="+s+"&email=abc@abc.com&www=http://wxq594808632.blog.163.com/";
var method = "POST";
function callBack(text){ //回調(diào)函數(shù)
alert("調(diào)用成功!\n名字為:"+text);
}
new Ajax().ajaxRequest(url,parameter,method,callBack); //調(diào)用方法發(fā)送Request
}
</script>
</head>
<body>
<input type="button" value="提交" onclick="doso()"/>
</body>
</html>
java類
ActAction.java
package ajaxpost;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.PrintWriter;
public class ActAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
UnsupportedEncodingException {
//設(shè)置字符編碼返回的編碼
response.setContentType("text/html;charset=UTF-8");
//接收字符的編碼
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException ex) {
ex.printStackTrace();
}
String name = request.getParameter("name");
String email = request.getParameter("email");
String www = request.getParameter("www");
System.out.println(email);
System.out.println(name);
System.out.println(www);
// out.print(name+"\n"+email+"\n"+www);
out.print(name); //返回值
return null;
}
}
最重要滴
ajax.js
我用別人的。感謝這位大哥。。
/*
author zhangshuling
email zhangshuling1214@126.com
*/
function Ajax(){
var _xmlHttp = null;
this.createXMLHttpRequest = function(){
try{
if (window.ActiveXObject) {
_xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
_xmlHttp = new XMLHttpRequest();
}
}catch(e){
alert(e.name +" : " + e.message);
}
}
this.backFunction = function(_backFunction){
if(_xmlHttp.readyState == 4) {
if(_xmlHttp.status == 200) {
_backFunction(_xmlHttp.responseText);//這里可以設(shè)置返回類型
}
}
_xmlHttp.onreadystatechange = null;
}
this.doPost = function(_url,_parameter,_backFunction){
try{
_xmlHttp.open("POST",_url, false);
_xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_xmlHttp.send(_parameter);
}catch(e){
alert(e.name +" : " + e.message);
}
}
this.doGet = function(_url,_parameter,_backFunction){
try{
var _random = Math.round(Math.random()*10000);
_xmlHttp.open("GET", (_url+"?random=" +_random +"&" + _parameter), false);
_xmlHttp.send(null);
}catch(e){
alert(e.name +" : " + e.message);
}
}
this.ajaxRequest = function(_url,_parameter,_method,_backFunction){
try{
this.createXMLHttpRequest();
if(_method.toLowerCase() == "post"){
this.doPost(_url,_parameter,_backFunction);
}else{
this.doGet(_url,_parameter,_backFunction);
}
try{
_xmlHttp.onreadystatechange = this.backFunction(_backFunction);
}catch(err){
//??????IE?????????????????
}
}catch(e){
alert(e.name +" : " + e.message);
}
}
}
/*
var url = "ajax.do";
var parameter = "parameter=parameter";
var method = "post"
function callBack(text){
....
}
new Ajax().ajaxRequest(url,parameter,method,callBack);
*/
經(jīng)過本人FF,IE6,IE7,測(cè)試。完全好用
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
public class Img2 {
//讀取遠(yuǎn)程url圖片,得到寬高
public int[] returnImgWH(String imgurl) {
boolean b=false;
try {
//實(shí)例化url
URL url = new URL(imgurl);
//載入圖片到輸入流
java.io.BufferedInputStream bis = new BufferedInputStream(url.openStream());
//實(shí)例化存儲(chǔ)字節(jié)數(shù)組
byte[] bytes = new byte[100];
//設(shè)置寫入路徑以及圖片名稱
OutputStream bos = new FileOutputStream(new File( "C:\\thetempimg.gif"));
int len;
while ((len = bis.read(bytes)) > 0) {
bos.write(bytes, 0, len);
}
bis.close();
bos.flush();
bos.close();
//關(guān)閉輸出流
b=true;
} catch (Exception e) {
//如果圖片未找到
b=false;
}
int[] a = new int[2];
if(b){ //圖片存在
//得到文件
java.io.File file = new java.io.File("C:\\thetempimg.gif");
BufferedImage bi = null;
try {
//讀取圖片
bi = javax.imageio.ImageIO.read(file);
} catch (IOException ex) {
ex.printStackTrace();
}
a[0] = bi.getWidth(); //獲得 寬度
a[1] = bi.getHeight(); //獲得 高度
//刪除文件
file.delete();
}else{ //圖片不存在
a=null;
}
return a;
}
public static void main(String[] args) {
Img2 i = new Img2();
int[] a=i.returnImgWH(" if(a==null){
System.out.println("圖片未找到!");
}else{
System.out.println("寬為" + a[0]);
System.out.println("高為" + a[1]);
}
}
}
如題
默認(rèn)排序方式為asc,可省略...
select * from table order by t1 desc, t2 desc , t3 desc;
function jsTrim(value)
{
var reg=/^\S$/;
if (!value) return "";
if(value.length==0)
return value;
else
{
var lp,rp;
lp=0;rp=value.length-1;
while ((value.charAt(lp)==" "||(value.charCodeAt(lp)<128?(reg.test(value.charAt(lp))==false?true:false):false)||value.charAt(rp)==" "||(value.charCodeAt(rp)<128?(reg.test(value.charAt(rp))==false?true:false):false))&&rp>=lp)
{
if (value.charAt(lp)==" "||value.charCodeAt(lp)<128?(reg.test(value.charAt(lp))==false?true:false):false)
lp++;
if (value.charAt(rp)==" "||value.charCodeAt(rp)<128?(reg.test(value.charAt(rp))==false?true:false):false)
rp--;
}
if(lp>rp)
return "";
else
return (value.substring(lp,rp+1));
}
}
引用
邵波的空間 的 Java實(shí)現(xiàn)給圖片添加水印
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.*;public class WaterMark ...{
/** *//**
* 給圖片添加水印
* @param filePath 需要添加水印的圖片的路徑
* @param markContent 水印的文字
* @param markContentColor 水印文字的顏色
* @param qualNum 圖片質(zhì)量
* @return
*/
public boolean createMark(String filePath,String markContent,Color markContentColor,float qualNum,String watermark)
...{
ImageIcon imgIcon=new ImageIcon(filePath);
Image theImg =imgIcon.getImage();
int width=theImg.getWidth(null);
int height= theImg.getHeight(null);
//ImageIcon waterIcon=new ImageIcon(watermark);
//Image waterImg =waterIcon.getImage();
BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bimage.createGraphics();
g.setColor(markContentColor);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null );
//g.drawImage(waterImg, width*2, height, null );
g.drawString(markContent,width-100,height-30); //添加水印的文字和設(shè)置水印文字出現(xiàn)的內(nèi)容
g.dispose();
try...{
FileOutputStream out=new FileOutputStream(filePath);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(qualNum, true);
encoder.encode(bimage, param);
out.close();
}catch(Exception e)
...{ return false; }
return true;
}
public static void main(String arg[])
...{
WaterMark wk=new WaterMark();
if(wk.createMark("D:\1.jpg","Welcome!",Color.WHITE,70f,""))...{
System.out.println("制作成功");
}else...{
System.out.println("失敗了!");
}
}
}
引用
邵波的空間 的 如何防止同一個(gè)賬戶被多個(gè)人同時(shí)登陸?
1.用session超時(shí),session為null就表示下線了
2.也可以采用數(shù)據(jù)庫中設(shè)置 臨時(shí)表 來處理
一個(gè)用戶登陸時(shí)向表中插進(jìn)一條記錄,用戶離開時(shí)候刪除該記錄
如想統(tǒng)計(jì)在線人數(shù),簡單地執(zhí)行
select count(*) from table... 即可
3.application對(duì)象中可以記住現(xiàn)在的人數(shù),application的生命周期和服務(wù)器的生命周期一樣長。
4.還有一種方法要用到一個(gè)文件global.jsa ,方法是(在JSP中)是sessionDestroy(),其中它是以session對(duì)象為參數(shù)的。還有要把global.jsa文件必須房子和JSP 程序 相同的文件目錄內(nèi)才行。
5.網(wǎng)頁自動(dòng)刷新的代碼是:
在文件頭部加上
<meta http-equiv="refresh" content="15">
刷新間隔時(shí)間是15秒
6.在session中加入監(jiān)聽類,類的示例代碼如下:onLineUser.java-------------------------------------------------------------------------------------------
package com.shaobo.struts.action;
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ǒng)\t"
+ (new Date()));
System.out.println("在線用戶數(shù)為:" + getCount());
} else
System.out.println(e.getName() + "已經(jīng)存在");
}public void valueUnbound(HttpSessionBindingEvent e) {
users.trimToSize();
String userName = e.getName();
deleteUser(userName);
System.out.print(userName + "\t退出系統(tǒng)\t" + (new Date()));
System.out.println("在線用戶數(shù)為:" + getCount());
}
}login.jsp--------------------------------------------------------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><jsp:useBean id="onlineuser" class="com.shaobo.struts.action.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>已經(jīng)登陸!");
} else {
session.setMaxInactiveInterval(50); //Sesion有效時(shí)長,以秒為單位
session.setAttribute(username, onlineuser);
out.println("歡迎新用戶:<font color=red>" + username
+ "</font>登陸到系統(tǒng)!");
}
out.println("<br>當(dāng)前在線用戶人數(shù):<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()">關(guān)閉窗口</a>]
<%
out.println("<p><a href='index.jsp'>退出系統(tǒng)</a></p>");
%>
</center>
<Script>
function postMessage(){
<%onlineuser.deleteUser(request.getParameter("username"));%>
}
</Script>
</body>
</html>歡迎光臨邵波的空間` http://blog.sina.com.cn/shaobolive
QQ:343269876
引用
邵波的空間 的 java中文件操作大全
一.獲得控制臺(tái)用戶輸入的信息
/**獲得控制臺(tái)用戶輸入的信息 * @return * @throws IOException */ public String getInputMessage() throws IOException...{ System.out.println("請(qǐng)輸入您的命令∶"); byte buffer[]=new byte[1024]; int count=System.in.read(buffer); char[] ch=new char[count-2];//最后兩位為結(jié)束符,刪去不要 for(int i=0;i<count-2;i++) ch[i]=(char)buffer[i]; String str=new String(ch); return str;
- /**獲得控制臺(tái)用戶輸入的信息
- * @return
- * @throws IOException
- */
- public String getInputMessage() throws IOException...{
- System.out.println("請(qǐng)輸入您的命令∶");
- byte buffer[]=new byte[1024];
- int count=System.in.read(buffer);
- char[] ch=new char[count-2];//最后兩位為結(jié)束符,刪去不要
- for(int i=0;i<count-2;i++)
- ch[i]=(char)buffer[i];
- String str=new String(ch);
- return str;
可以返回用戶輸入的信息,不足之處在于不支持中文輸入,有待進(jìn)一步改進(jìn)
二.復(fù)制文件
以文件流的方式復(fù)制文件
**以文件流的方式復(fù)制文件 * @param src 文件源目錄 * @param dest 文件目的目錄 * @throws IOException */ public void copyFile(String src,String dest) throws IOException...{ FileInputStream in=new FileInputStream(src); File file=new File(dest); if(!file.exists()) file.createNewFile(); FileOutputStream out=new FileOutputStream(file); int c; byte buffer[]=new byte[1024]; while((c=in.read(buffer))!=-1)...{ for(int i=0;i<c;i++) out.write(buffer[i]); } in.close(); out.close();
- **以文件流的方式復(fù)制文件
- * @param src 文件源目錄
- * @param dest 文件目的目錄
- * @throws IOException
- */
- public void copyFile(String src,String dest) throws IOException...{
- FileInputStream in=new FileInputStream(src);
- File file=new File(dest);
- if(!file.exists())
- file.createNewFile();
- FileOutputStream out=new FileOutputStream(file);
- int c;
- byte buffer[]=new byte[1024];
- while((c=in.read(buffer))!=-1)...{
- for(int i=0;i<c;i++)
- out.write(buffer[i]);
- }
- in.close();
- out.close();
該方法經(jīng)過測(cè)試,支持中文處理,并且可以復(fù)制多種類型,比如txt,xml,jpg,doc等多種格式
三.寫文件
1.利用PrintStream寫文件
/** * 文件輸出示例 */ public void PrintStreamDemo()...{ try ...{ FileOutputStream out=new FileOutputStream("D:/test.txt"); PrintStream p=new PrintStream(out); for(int i=0;i<10;i++) p.println("This is "+i+" line"); } catch (FileNotFoundException e) ...{ e.printStackTrace(); } }
- /**
- * 文件輸出示例
- */
- public void PrintStreamDemo()...{
- try ...{
- FileOutputStream out=new FileOutputStream("D:/test.txt");
- PrintStream p=new PrintStream(out);
- for(int i=0;i<10;i++)
- p.println("This is "+i+" line");
- } catch (FileNotFoundException e) ...{
- e.printStackTrace();
- }
- }
2.利用StringBuffer寫文件
public void StringBufferDemo() throws IOException......{ File file=new File("/root/sms.log"); if(!file.exists()) file.createNewFile(); FileOutputStream out=new FileOutputStream(file,true); for(int i=0;i<10000;i++)......{ StringBuffer sb=new StringBuffer(); sb.append("這是第"+i+"行:前面介紹的各種方法都不關(guān)用,為什么總是奇怪的問題 "); out.write(sb.toString().getBytes("utf-8")); } out.close(); }
- public void StringBufferDemo() throws IOException......{
- File file=new File("/root/sms.log");
- if(!file.exists())
- file.createNewFile();
- FileOutputStream out=new FileOutputStream(file,true);
- for(int i=0;i<10000;i++)......{
- StringBuffer sb=new StringBuffer();
- sb.append("這是第"+i+"行:前面介紹的各種方法都不關(guān)用,為什么總是奇怪的問題 ");
- out.write(sb.toString().getBytes("utf-8"));
- }
- out.close();
- }
該方法可以設(shè)定使用何種編碼,有效解決中文問題。
四.文件重命名
/** *//**文件重命名 * @param path 文件目錄 * @param oldname 原來的文件名 * @param newname 新文件名 */ public void renameFile(String path,String oldname,String newname)...{ if(!oldname.equals(newname))...{//新的文件名和以前文件名不同時(shí),才有必要進(jìn)行重命名 File oldfile=new File(path+"/"+oldname); File newfile=new File(path+"/"+newname); if(newfile.exists())//若在該目錄下已經(jīng)有一個(gè)文件和新文件名相同,則不允許重命名 System.out.println(newname+"已經(jīng)存在!"); else...{ oldfile.renameTo(newfile); } } }
- /** *//**文件重命名
- * @param path 文件目錄
- * @param oldname 原來的文件名
- * @param newname 新文件名
- */
- public void renameFile(String path,String oldname,String newname)...{
- if(!oldname.equals(newname))...{//新的文件名和以前文件名不同時(shí),才有必要進(jìn)行重命名
- File oldfile=new File(path+"/"+oldname);
- File newfile=new File(path+"/"+newname);
- if(newfile.exists())//若在該目錄下已經(jīng)有一個(gè)文件和新文件名相同,則不允許重命名
- System.out.println(newname+"已經(jīng)存在!");
- else...{
- oldfile.renameTo(newfile);
- }
- }
- }
五.轉(zhuǎn)移文件目錄
轉(zhuǎn)移文件目錄不等同于復(fù)制文件,復(fù)制文件是復(fù)制后兩個(gè)目錄都存在該文件,而轉(zhuǎn)移文件目錄則是轉(zhuǎn)移后,只有新目錄中存在該文件。
- /**轉(zhuǎn)移文件目錄
- * @param filename 文件名
- * @param oldpath 舊目錄
- * @param newpath 新目錄
- * @param cover 若新目錄下存在和轉(zhuǎn)移文件具有相同文件名的文件時(shí),是否覆蓋新目錄下文件,cover=true將會(huì)覆蓋原文件,否則不操作
- */
- public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{
if(!oldpath.equals(newpath))...{ File oldfile=new File(oldpath+"/"+filename); File newfile=new File(newpath+"/"+filename); if(newfile.exists())...{//若在待轉(zhuǎn)移目錄下,已經(jīng)存在待轉(zhuǎn)移文件 if(cover)//覆蓋 oldfile.renameTo(newfile); else System.out.println("在新目錄下已經(jīng)存在:"+filename); } else...{ oldfile.renameTo(newfile); } } } /**轉(zhuǎn)移文件目錄 * @param filename 文件名 * @param oldpath 舊目錄 * @param newpath 新目錄 * @param cover 若新目錄下存在和轉(zhuǎn)移文件具有相同文件名的文件時(shí),是否覆蓋新目錄下文件,cover=true將會(huì)覆蓋原文件,否則不操作 */ public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{ if(!oldpath.equals(newpath))...{ File oldfile=new File(oldpath+"/"+filename); File newfile=new File(newpath+"/"+filename); if(newfile.exists())...{//若在待轉(zhuǎn)移目錄下,已經(jīng)存在待轉(zhuǎn)移文件 if(cover)//覆蓋 oldfile.renameTo(newfile); else System.out.println("在新目錄下已經(jīng)存在:"+filename); } else...{ oldfile.renameTo(newfile); } } }
六.讀文件
1.利用FileInputStream讀取文件
- /** *//**讀文件
- * @param path
- * @return
- * @throws IOException
- */
- public String FileInputStreamDemo(String path) throws IOException...{
File file=new File(path); if(!file.exists()||file.isDirectory()) throw new FileNotFoundException(); FileInputStream fis=new FileInputStream(file); byte[] buf = new byte[1024]; StringBuffer sb=new StringBuffer(); while((fis.read(buf))!=-1)...{ sb.append(new String(buf)); buf=new byte[1024];//重新生成,避免和上次讀取的數(shù)據(jù)重復(fù) } return sb.toString(); } /** *//**讀文件 * @param path * @return * @throws IOException */ public String FileInputStreamDemo(String path) throws IOException...{ File file=new File(path); if(!file.exists()||file.isDirectory()) throw new FileNotFoundException(); FileInputStream fis=new FileInputStream(file); byte[] buf = new byte[1024]; StringBuffer sb=new StringBuffer(); while((fis.read(buf))!=-1)...{ sb.append(new String(buf)); buf=new byte[1024];//重新生成,避免和上次讀取的數(shù)據(jù)重復(fù) } return sb.toString(); }
2.利用BufferedReader讀取在IO操作,利用BufferedReader和BufferedWriter效率會(huì)更高一點(diǎn)
- /** *//**讀文件
- * @param path
- * @return
- * @throws IOException
- */
- public String BufferedReaderDemo(String path) throws IOException...{
引用
邵波的空間 的 Javamail操作指南
怎樣才算比較完整的Javamail操作指南?我想應(yīng)該包括絕大多數(shù)基本的email操作,能夠應(yīng)付一般的應(yīng)用。在本指南中打算囊括以下內(nèi)容:● 發(fā)送email:包括文本郵件、HTML郵件、帶附件的郵件、SMTP驗(yàn)證
● 接收email:pop3遠(yuǎn)程連接、收取不同MIME的郵件、處理附件我想有了上述功能的介紹,應(yīng)該可以應(yīng)付很多email的相關(guān)應(yīng)用了。所以請(qǐng)?jiān)试S我給本文擬了一個(gè)比較狂妄的名字,這樣才能保證收視率,。還是那句話,寫這個(gè)post的原因就是沒有在網(wǎng)上看到更全面的,你看過的話記得要告訴我。
下面的所有例子都經(jīng)過實(shí)際測(cè)試,你可以說它寫得不夠OO,不夠plugable,但是它的確是可以參考的。自從有了javamail,發(fā)垃圾郵件就方便多了。本文代碼多說明少,這倒不是我偷懶,而是很多東西都涉及pop3等協(xié)議的規(guī)范,如果不了解這些規(guī)范的話,由的東西我實(shí)在不知道怎么跟你解釋;如果了解的話,那我基本上就不用再解釋。所以本著實(shí)用的原則就省略了,由興趣的話自己去翻翻協(xié)議規(guī)范。
廢話少說,首先需要配置環(huán)境。需要的包是mail.jar和activation.jar。高版本的J2SDK EE自帶。地址嘛,再java.sun.com上搜索一下,很容易找到。放到classpath中就KO。
一、 郵件的發(fā)送
下面了弄個(gè)發(fā)郵件的Hello World,熱熱身:
/*************
Name:TextMailSender.java
Author:Bromon
Version:1.0
Date:2004-4-26
Note:發(fā)送email到bromon@163.com,需要安裝SMTP服務(wù)器
*************/
package org.bromon.mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class TextMailSender
{
public static void main(String args[])
{
try
{
Properties prop=new Properties();
//指定要使用的SMTP服務(wù)器為bromon2k
prop.put("mail.smtp.host","bromon2k");
Session mailSession=Session.getDefaultInstance(prop);//發(fā)件人地址
InternetAddress from=new InternetAddress("bromon@bromon2k");
//收件人地址
InternetAddress to=new InternetAddress("bromon@163.com");
MimeMessage msg=new MimeMessage(mailSession);
msg.setFrom(from);
msg.addRecipient(javax.mail.Message.RecipientType.TO,to);
//發(fā)信日期
msg.setSentDate(new java.util.Date());
//title
msg.setSubject("你好");
//郵件正文
msg.setText("hello,bromon");
Transport.send(msg);
}catch(Exception e)
{
System.out.println(e);
}
}
}
程序很簡單,但是它是不能運(yùn)行的(倒)。除非你的機(jī)器上安裝了一個(gè)SMTP服務(wù)器,而且你的機(jī)器還叫做bromon2k。寫這么一段不能執(zhí)行的程序不是為了找打,而是讓各位對(duì)javamail有個(gè)基本印象,我就懶得改了。下面演示的是如何通過163、sohu等email服務(wù)商提供的免費(fèi)郵箱來發(fā)郵件,基本操作和上面的一樣,只是多一個(gè)SMTP驗(yàn)證而已:/*
* Created on 2004-4-26
*/
package org.bromon.mail;
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;/**
* @author Bromon
*/
public class SenderWithSMTPVer
{
String host="";
String user="";
String password="";public void setHost(String host)
{
this.host=host;
}public void setAccount(String user,String password)
{
this.user=user;
this.password=password;
}public void send(String from,String to,String subject,String content)
{
Properties props = new Properties();
props.put("mail.smtp.host", host);//指定SMTP服務(wù)器
props.put("mail.smtp.auth", "true");//指定是否需要SMTP驗(yàn)證
try
{
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制臺(tái)顯示debug信息
Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//發(fā)件人
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人
message.setSubject(subject);//郵件主題
message.setText(content);//郵件內(nèi)容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch(Exception e)
{
System.out.println(e);
}
}public static void main(String args[])
{
SenderWithSMTPVer sm=new SenderWithSMTPVer();sm.setHost("smtp.163.com");//指定要使用的郵件服務(wù)器
sm.setAccount("abc","123");//指定帳號(hào)和密碼/*
* @param String 發(fā)件人的地址
* @param String 收件人地址
* @param String 郵件標(biāo)題
* @param String 郵件正文
*/
sm.send("abc@163.com","bromon@163.com","標(biāo)題","內(nèi)容");
}}
這段程序好像也不需要解釋了吧,把SMTP地址、帳號(hào)、密碼等配置信息寫到Properties里面,Java里面很多API都需要這么干,比如再程序中加入對(duì)代理服務(wù)器的支持等。上面的程序修改一下服務(wù)器地址、帳號(hào)、密碼就可以使用,非常簡單。
如何發(fā)送一個(gè)HTML格式的Email呢?也很簡單,再郵件正文中寫入HTML代碼,然后指定郵件的ContentType就OK,下面只給出關(guān)鍵代碼:
………..
MimeMessage msg=new MimeMessage(mailSession);
msg.setContent(content,"text/html");
msg.setText(“<html><body><h1>下面的,你們好嗎?</body></html>”);
………..下面是發(fā)送帶有附件的email,稍微復(fù)雜一點(diǎn),而且和前面的程序有一些不同,請(qǐng)仔細(xì)一點(diǎn),同時(shí)需要一點(diǎn)IO的知識(shí)。相同的代碼就不在列出,只寫關(guān)鍵部分,誰都想偷懶不是?
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
……….
MimeMessage msg=new MimeMessage(mailSession);
msg.setSentDate(new Date());
msg.setSubject("hello");MimeBodyPart textBodyPart=new MimeBodyPart();
textBodyPart.setText(“郵件正文”);MimeBodyPart fileBodyPart=new MimeBodyPart();
FileDataSource fds=new FileDataSource("GIS.rar");//要發(fā)送的附件
fileBodyPart.setDataHandler(new DataHandler(fds));
fileBodyPart.setFileName(fds.getName());
Multipart container=new MimeMultipart();
container.addBodyPart(textBodyPart);
container.addBodyPart(fileBodyPart);
msg.setContent(container);
Transport.send(msg);
…………二、 郵件的收取
這里的msg由兩個(gè)MimeBodyPart構(gòu)成,這個(gè)東西解釋起來基本上比較難,如果不了解相關(guān)的規(guī)范就不太好解釋,如果了解的話,我就不用解釋了,這個(gè)這個(gè)………唉。
通常情況下我們都使用pop3協(xié)議來收郵件,IMAP嘛現(xiàn)在就不涉及了。收郵件的功能雖然我用了很多時(shí)間才基本搞清楚,不過講起來就so easy了,一個(gè)程序就可以基本包括。
郵件大致可以分三種:純文本郵件、含有其他數(shù)據(jù)的文本郵件、含有附件的郵件。
CODE
/*
* Created on 2004-4-26
*/
package org.bromon.mail;
import javax.mail.*;
import java.util.*;
import java.io.*;/**
* @author Bromon
*/
public class Receiver
{
Folder inbox;
Store store;//連接郵件服務(wù)器,獲得所有郵件的列表
public Message[] getMail(String host,String name,String password) throws Exception
{
Properties prop=new Properties();
prop.put("mail.pop3.host",host);
Session session=Session.getDefaultInstance(prop);
store=session.getStore("pop3");
store.connect(host,name,password);
inbox=store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msg=inbox.getMessages();
FetchProfile profile=new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
inbox.fetch(msg,profile);
return(msg);
}//處理任何一種郵件都需要的方法
private void handle(Message msg) throws Exception
{
System.out.println("郵件主題:"+msg.getSubject());
System.out.println("郵件作者:"+msg.getFrom()[0].toString());
System.out.println("發(fā)送日期:"+msg.getSentDate());
}//處理文本郵件
public void handleText(Message msg) throws Exception
{
this.handle(msg);
System.out.println("郵件內(nèi)容:"+msg.getContent());
}//處理Multipart郵件,包括了保存附件的功能
public void handleMultipart(Message msg) throws Exception
{
String disposition;
BodyPart part;
Multipart mp=(Multipart)msg.getContent();
int mpCount=mp.getCount();//Miltipart的數(shù)量,用于除了多個(gè)part,比如多個(gè)附件
for(int m=0;m<mpCount;m++)
{
this.handle(msg);
part=mp.getBodyPart(m);
disposition=part.getDisposition();
if(disposition!=null && disposition.equals(Part.ATTACHMENT))//判斷是否有附件
{
//this.saveAttach(part);//這個(gè)方法負(fù)責(zé)保存附件,注釋掉是因?yàn)楦郊赡苡胁《?,?qǐng)清理信箱之后再取掉注釋
}else{
System.out.println(part.getContent());
}
}
}private void saveAttach(BodyPart part) throws Exception
{
String temp=part.getFileName();//得到未經(jīng)處理的附件名字
String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer
//文件名一般都經(jīng)過了base64編碼,下面是解碼
String fileName=this.base64Decoder(s);
System.out.println("有附件:"+fileName);
InputStream in=part.getInputStream();
FileOutputStream writer=new FileOutputStream(new File(fileName));
byte[] content=new byte[255];
int read=0;
while((read=in.read(content))!=-1)
{
writer.write(content);
}
writer.close();
in.close();
}//base64解碼
private String base64Decoder(String s) throws Exception
{
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b=decoder.decodeBuffer(s);
return(new String(b));
}//關(guān)閉連接
public void close() throws Exception
{
if(inbox!=null)
{
inbox.close(false);
}
if(store!=null)
{
store.close();
}
}public static void main(String args[])
{
String host="pop.163.com";
String name="bromon";
String password="My password";
Receiver receiver=new Receiver();
try
{
Message[] msg=receiver.getMail(host,name,password);
for(int i=0;i<msg.length;i++)
{
if(msg[i].isMimeType("text/*"))//判斷郵件類型
{
receiver.handleText(msg[i]);
}else{
receiver.handleMultipart(msg[i]);
}
System.out.println("****************************");
}
receiver.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
沒有習(xí)慣讀java代碼的兄弟可能會(huì)覺得麻煩了一點(diǎn),其中有個(gè)小問題,下載的附件會(huì)再文件名后面加上一個(gè)”#”符號(hào),不知道這是javamail的特別處理還是pop3的規(guī)范。通過程序更改文件名很簡單,就不說了。對(duì)于email還有很多其他的操作,可以自己取查看一下javadoc,我就不影響大家探索的樂趣了。在Properties里配置代理服務(wù)器,可以讓程序通過代理收發(fā)郵件,一般的HTTP、socks 4、socks 5都支持。
引用
邵波的空間 的 java的幾種對(duì)象(PO,VO,DAO,BO,POJO)解釋
一、PO:persistant object 持久對(duì)象,可以看成是與數(shù)據(jù)庫中的表相映射的java對(duì)象。最簡單的PO就是對(duì)應(yīng)數(shù)據(jù)庫中某個(gè)表中的一條記錄,多個(gè)記錄可以用PO的集合。PO中應(yīng)該不包含任何對(duì)數(shù)據(jù)庫的操作。
二、VO:value object值對(duì)象。通常用于業(yè)務(wù)層之間的數(shù)據(jù)傳遞,和PO一樣也是僅僅包含數(shù)據(jù)而已。但應(yīng)是抽象出的業(yè)務(wù)對(duì)象,可以和表對(duì)應(yīng),也可以不,這根據(jù)業(yè)務(wù)的需要.個(gè)人覺得同DTO(數(shù)據(jù)傳輸對(duì)象),在web上傳遞。
三、DAO:data access object 數(shù)據(jù)訪問對(duì)象,此對(duì)象用于訪問數(shù)據(jù)庫。通常和PO結(jié)合使用,DAO中包含了各種數(shù)據(jù)庫的操作方法。通過它的方法,結(jié)合PO對(duì)數(shù)據(jù)庫進(jìn)行相關(guān)的操作。
四、BO:business object 業(yè)務(wù)對(duì)象,封裝業(yè)務(wù)邏輯的java對(duì)象,通過調(diào)用DAO方法,結(jié)合PO,VO進(jìn)行業(yè)務(wù)操作。
五、POJO:plain ordinary java object 簡單無規(guī)則java對(duì)象,我個(gè)人覺得它和其他不是一個(gè)層面上的東西,VO和PO應(yīng)該都屬于它。
O/R Mapping 是 Object Relational Mapping(對(duì)象關(guān)系映射)的縮寫。通俗點(diǎn)講,就是將對(duì)象與關(guān)系數(shù)據(jù)庫綁定,用對(duì)象來表示關(guān)系數(shù)據(jù)。在O/R Mapping的世界里,有兩個(gè)基本的也是重要的東東需要了解,即VO,PO。
VO,值對(duì)象(Value Object),PO,持久對(duì)象(Persisent Object),它們是由一組屬性和屬性的get和set方法組成。從結(jié)構(gòu)上看,它們并沒有什么不同的地方。但從其意義和本質(zhì)上來看是完全不同的。
1.VO是用new關(guān)鍵字創(chuàng)建,由GC回收的。
PO則是向數(shù)據(jù)庫中添加新數(shù)據(jù)時(shí)創(chuàng)建,刪除數(shù)據(jù)庫中數(shù)據(jù)時(shí)削除的。并且它只能存活在一個(gè)數(shù)據(jù)庫連接中,斷開連接即被銷毀。
2.VO是值對(duì)象,精確點(diǎn)講它是業(yè)務(wù)對(duì)象,是存活在業(yè)務(wù)層的,是業(yè)務(wù)邏輯使用的,它存活的目的就是為數(shù)據(jù)提供一個(gè)生存的地方。
PO則是有狀態(tài)的,每個(gè)屬性代表其當(dāng)前的狀態(tài)。它是物理數(shù)據(jù)的對(duì)象表示。使用它,可以使我們的程序與物理數(shù)據(jù)解耦,并且可以簡化對(duì)象數(shù)據(jù)與物理數(shù)據(jù)之間的轉(zhuǎn)換。
3.VO的屬性是根據(jù)當(dāng)前業(yè)務(wù)的不同而不同的,也就是說,它的每一個(gè)屬性都一一對(duì)應(yīng)當(dāng)前業(yè)務(wù)邏輯所需要的數(shù)據(jù)的名稱。
PO的屬性是跟數(shù)據(jù)庫表的字段一一對(duì)應(yīng)的。
PO對(duì)象需要實(shí)現(xiàn)序列化接口。
引用
邵波的空間 的 JS通用表單驗(yàn)證函數(shù)
Check.js JS函數(shù)文件
////////////////////////////////////////////////////////////////////////////////
/*
*--------------- 客戶端表單通用驗(yàn)證CheckForm(oForm) -----------------
* 功能:通用驗(yàn)證所有的表單元素.
* 使用:
* <form name="form1" onsubmit="return CheckForm(this)">
* <input type="text" name="id" check="^\S+$" warning="id不能為空,且不能含有空格">
* <input type="submit">
* </form>
* author:wanghr100(灰豆寶寶.net)
* email:wanghr100@126.com
* update:19:28 2004-8-23
* 注意:寫正則表達(dá)式時(shí)一定要小心.不要讓"有心人"有空子鉆.
* 已實(shí)現(xiàn)功能:
* 對(duì)text,password,hidden,file,textarea,select,radio,checkbox進(jìn)行合法性驗(yàn)證
* 待實(shí)現(xiàn)功能:把正則表式寫成個(gè)庫.
*--------------- 客戶端表單通用驗(yàn)證CheckForm(oForm) -----------------
*/
////////////////////////////////////////////////////////////////////////////////
//主函數(shù)
function CheckForm(oForm)
{
var els = oForm.elements;
//遍歷所有表元素
for(var i=0;i<els.length;i++)
{
//是否需要驗(yàn)證
if(els[i].check)
{
//取得驗(yàn)證的正則字符串
var sReg = els[i].check;
//取得表單的值,用通用取值函數(shù)
var sVal = GetValue(els[i]);
//字符串->正則表達(dá)式,不區(qū)分大小寫
var reg = new RegExp(sReg,"i");
if(!reg.test(sVal))
{
//驗(yàn)證不通過,彈出提示warning
alert(els[i].warning);
//該表單元素取得焦點(diǎn),用通用返回函數(shù)
GoBack(els[i])
return false;
}
}
}
}
//通用取值函數(shù)分三類進(jìn)行取值
//文本輸入框,直接取值el.value
//單多選,遍歷所有選項(xiàng)取得被選中的個(gè)數(shù)返回結(jié)果"00"表示選中兩個(gè)
//單多下拉菜單,遍歷所有選項(xiàng)取得被選中的個(gè)數(shù)返回結(jié)果"0"表示選中一個(gè)
function GetValue(el)
{
//取得表單元素的類型
var sType = el.type;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "file":
case "textarea": return el.value;
case "checkbox":
case "radio": return GetValueChoose(el);
case "select-one":
case "select-multiple": return GetValueSel(el);
}
//取得radio,checkbox的選中數(shù),用"0"來表示選中的個(gè)數(shù),我們寫正則的時(shí)候就可以通過0{1,}來表示選中個(gè)數(shù)
function GetValueChoose(el)
{
var sValue = "";
//取得第一個(gè)元素的name,搜索這個(gè)元素組
var tmpels = document.getElementsByName(el.name);
for(var i=0;i<tmpels.length;i++)
{
if(tmpels[i].checked)
{
sValue += "0";
}
}
return sValue;
}
//取得select的選中數(shù),用"0"來表示選中的個(gè)數(shù),我們寫正則的時(shí)候就可以通過0{1,}來表示選中個(gè)數(shù)
function GetValueSel(el)
{
var sValue = "";
for(var i=0;i<el.options.length;i++)
{
//單選下拉框提示選項(xiàng)設(shè)置為value=""
if(el.options[i].selected && el.options[i].value!="")
{
sValue += "0";
}
}
return sValue;
}
}
//通用返回函數(shù),驗(yàn)證沒通過返回的效果.分三類進(jìn)行取值
//文本輸入框,光標(biāo)定位在文本輸入框的末尾
//單多選,第一選項(xiàng)取得焦點(diǎn)
//單多下拉菜單,取得焦點(diǎn)
function GoBack(el)
{
//取得表單元素的類型
var sType = el.type;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "file":
case "textarea": el.focus();var rng = el.createTextRange(); rng.collapse(false); rng.select();
case "checkbox":
case "radio": var els = document.getElementsByName(el.name);els[0].focus();
case "select-one":
case "select-multiple":el.focus();
}
}
demo.htm 演示文件
<script language="JavaScript" src="Check.js"></script>
通用表單函數(shù)測(cè)試:
<form name="form1" onsubmit="return CheckForm(this)">
test:<input type="text" name="test">不驗(yàn)證<br>
賬號(hào):<input type="text" check="^\S+$" warning="賬號(hào)不能為空,且不能含有空格" name="id">不能為空<br>
密碼:<input type="password" check="\S{6,}" warning="密碼六位以上" name="id">六位以上<br>
電話:<input type="text" check="^\d+$" warning="電話號(hào)碼含有非法字符" name="number" value=""><br>
相片上傳:<input type="file" check="(.*)(\.jpg|\.bmp)$" warning="相片應(yīng)該為JPG,BMP格式的" name="pic" value="1"><br>
出生日期:<input type="text" check="^\d{4}\-\d{1,2}-\d{1,2}$" warning="日期格式2004-08-10" name="dt" value="">日期格式2004-08-10<br>
省份:
<select name="sel" check="^0$" warning="請(qǐng)選擇所在省份">
<option value="">請(qǐng)選擇
<option value="1">福建省
<option value="2">湖北省
</select>
<br>
選擇你喜歡的運(yùn)動(dòng):<br>
游泳<input type="checkbox" name="c" check="^0{2,}$" warning="請(qǐng)選擇2項(xiàng)或以上">
籃球<input type="checkbox" name="c">
足球<input type="checkbox" name="c">
排球<input type="checkbox" name="c">
<br>
你的學(xué)歷:
大學(xué)<input type="radio" name="r" check="^0$" warning="請(qǐng)選擇一項(xiàng)學(xué)歷">
中學(xué)<input type="radio" name="r">
小學(xué)<input type="radio" name="r">
<br>
個(gè)人介紹:
<textarea name="txts" check="^[\s|\S]{20,}$" warning="個(gè)人介紹不能為空,且不少于20字"></textarea>20個(gè)字以上
<input type="submit">
</form>不管是動(dòng)態(tài)網(wǎng)站,還是其它B/S結(jié)構(gòu)的系統(tǒng),都離不開表單
表單做為客戶端向服務(wù)器提交數(shù)據(jù)的載體擔(dān)當(dāng)相當(dāng)重要的角色.
這就引出了一個(gè)問題,提交的數(shù)據(jù)合法嗎?擺在我們面前的問題就是驗(yàn)證這些數(shù)據(jù)
保證所提交的數(shù)據(jù)是合法的.所以,我們寫了一個(gè)大堆的驗(yàn)證函數(shù).當(dāng)我們開始新的一個(gè)
項(xiàng)目的開發(fā)時(shí),我們又得寫一大堆的驗(yàn)證函數(shù),然后再調(diào)試這一大堆的函數(shù)...
本文將介紹一種方法來提高我的代碼的可重用性,提高我們的開發(fā)效率.
個(gè)人以為表單的驗(yàn)證應(yīng)該包含兩部分:
第一,判斷用戶輸入的數(shù)據(jù)是否合法.
第二,提示用戶你的數(shù)據(jù)為什么是不合法的.
所以,我們的通用表單驗(yàn)證函數(shù)要實(shí)現(xiàn)的功能就是:
第一,取得用戶輸入的數(shù)據(jù)GetValue(el)
第二,驗(yàn)證用戶的數(shù)據(jù)CheckForm(oForm)
IE支持自定義屬性,這就是這個(gè)通用函數(shù)實(shí)現(xiàn)的基礎(chǔ)
我們可以在表單元素上加入描述自身信息的屬性.有點(diǎn)像XML吧.
check屬性:該屬性用于存儲(chǔ)數(shù)據(jù)合法性的正則表達(dá)式.
warning屬性:該性性用于存儲(chǔ)出錯(cuò)誤提示信息.
第三,返回有誤的表單提示GoBack(el)
這三個(gè)步驟的觸發(fā)事件是onsubmit,記住是return CheckForm(this)
搞錯(cuò)了就全功盡棄了 :)
<form onsubmit="return CheckForm(this)">
寫到這里,整體框架就出來了,通過取得表單元素的check屬性,取得字符串,構(gòu)建正則表達(dá)式.再驗(yàn)證其值.如果通過驗(yàn)證就提交,如是數(shù)據(jù)不合法則取得表單元素的warning屬性,產(chǎn)生提示信息.并返回到該表單元素.整個(gè)的框架也比較簡單.
我們要做的就是寫好正則表達(dá)式!
接下來我們來分析一下所有的表單元素
按其共性,我們將它們分為三類
每類表單的特點(diǎn)不一樣,我們的目標(biāo)就是寫出通用的.
1.文輸入框Text
<input type="text" name="txt">
<input type="password" name="pwd">
<input type="hidden" name="hid">
<input type="file" name="myfile">
<textarea name="txts"></textarea>
2.單多選框Choose
<input type="checkbox" name="c">
<input type="checkbox" name="c">
<input type="radio" name="r">
<input type="radio" name="r">
3.單多下拉菜單Select
<select name="sel"></select>
<select name="sels" multiple></select>
講了一堆"大道理"太抽象了,代碼更有說服力!
引用
邵波的空間 的 JavaScript密碼強(qiáng)度檢測(cè)源代碼
1.Body代碼部分
- <body>
- <h4>密碼強(qiáng)度檢測(cè)</h4>
- <table width="100%" border="0" cellspacing="1" cellpadding="0">
- <tr>
- <td width="100" align="right">強(qiáng)度顯示:</td>
- <td>
- <script language="javascript">
- var ps = new PasswordStrength();
- ps.setSize("200","20");
- ps.setMinLength(5);
- </script>
- </td>
- </tr>
- <tr>
- <td align="right">密碼檢測(cè):</td>
- <td><input name="pwd" type="password" id="pwd" style="width:200px" onKeyUp="ps.update(this.value);"></td>
- </tr>
- </table>
- </body>
2.JS代碼部分
- //密碼強(qiáng)度;
- function PasswordStrength(showed){
- this.showed = (typeof(showed) == "boolean")?showed:true;
- this.styles = new Array();
- this.styles[0] = {backgroundColor:"#EBEBEB",borderLeft:"solid 1px #FFFFFF",borderRight:"solid 1px #BEBEBE",borderBottom:"solid 1px #BEBEBE"};
- this.styles[1] = {backgroundColor:"#FF4545",borderLeft:"solid 1px #FFFFFF",borderRight:"solid 1px #BB2B2B",borderBottom:"solid 1px #BB2B2B"};
- this.styles[2] = {backgroundColor:"#FFD35E",borderLeft:"solid 1px #FFFFFF",borderRight:"solid 1px #E9AE10",borderBottom:"solid 1px #E9AE10"};
- this.styles[3] = {backgroundColor:"#95EB81",borderLeft:"solid 1px #FFFFFF",borderRight:"solid 1px #3BBC1B",borderBottom:"solid 1px #3BBC1B"};
- this.labels= ["弱","中","強(qiáng)"];
- this.divName = "pwd_div_"+Math.ceil(Math.random()*100000);
- this.minLen = 5;
- this.width = "150px";
- this.height = "16px";
- this.content = "";
- this.selectedIndex = 0;
- this.init();
- }
- PasswordStrength.prototype.init = function(){
- var s = '<table cellpadding="0" id="'+this.divName+'_table" cellspacing="0" style="width:'+this.width+';height:'+this.height+';">';
- s += '<tr>';
- for(var i=0;i<3;i++){
- s += '<td id="'+this.divName+'_td_'+i+'" width="33%" align="center"><span style="font-size:1px"> </span><span id="'+this.divName+'_label_'+i+'" style="display:none;font-family: Courier New, Courier, mono;font-size: 12px;color: #000000;">'+this.labels[i]+'</span></td>';
- }
- s += '</tr>';
- s += '</table>';
- this.content = s;
- if(this.showed){
- document.write(s);
- this.copyToStyle(this.selectedIndex);
- }
- }
- PasswordStrength.prototype.copyToObject = function(o1,o2){
- for(var i in o1){
- o2[i] = o1[i];
- }
- }
- PasswordStrength.prototype.copyToStyle = function(id){
- this.selectedIndex = id;
- for(var i=0;i<3;i++){
- if(i == id-1){
- this.$(this.divName+"_label_"+i).style.display = "inline";
- }else{
- this.$(this.divName+"_label_"+i).style.display = "none";
- }
- }
- for(var i=0;i<id;i++){
- this.copyToObject(this.styles[id],this.$(this.divName+"_td_"+i).style);
- }
- for(;i<3;i++){
- this.copyToObject(this.styles[0],this.$(this.divName+"_td_"+i).style);
- }
- }
- PasswordStrength.prototype.$ = function(s){
- return document.getElementById(s);
- }
- PasswordStrength.prototype.setSize = function(w,h){
- this.width = w;
- this.height = h;
- }
- PasswordStrength.prototype.setMinLength = function(n){
- if(isNaN(n)){
- return ;
- }
- n = Number(n);
- if(n>1){
- this.minLength = n;
- }
- }
- PasswordStrength.prototype.setStyles = function(){
- if(arguments.length == 0){
- return ;
- }
- for(var i=0;i<arguments.length && i < 4;i++){
- this.styles[i] = arguments[i];
- }
- this.copyToStyle(this.selectedIndex);
- }
- PasswordStrength.prototype.write = function(s){
- if(this.showed){
- return ;
- }
- var n = (s == 'string') ? this.$(s) : s;
- if(typeof(n) != "object"){
- return ;
- }
- n.innerHTML = this.content;
- this.copyToStyle(this.selectedIndex);
- }
- PasswordStrength.prototype.update = function(s){
- if(s.length < this.minLen){
- this.copyToStyle(0);
- return;
- }
- var ls = -1;
- if (s.match(/[a-z]/ig)){
- ls++;
- }
- if (s.match(/[0-9]/ig)){
- ls++;
- }
- if (s.match(/(.[^a-z0-9])/ig)){
- ls++;
- }
- if (s.length < 6 && ls > 0){
- ls--;
- }
- switch(ls) {
- case 0:
- this.copyToStyle(1);
- break;
- case 1:
- this.copyToStyle(2);
- break;
- case 2:
- this.copyToStyle(3);
- break;
- default:
- this.copyToStyle(0);
- }
- }
引用
邵波的空間 的 javascript 取table中內(nèi)容
1,有如下表格,我們要取第2行第2列的值<table id="table1"><tr><td>1行1列</td><td>1行2列</td></tr><tr><td>2行1列</td><td>2行2列</td></tr></table>2,取值方法var value==window.table1.rows.item(0).cells.item(0).innerText;注意:行號(hào),列號(hào)是從 0 開始的例如 var value =window.table1.rows.item(1).cells.item(1).innerText;這就取到了第2行第2列的值3.改進(jìn)方法上面的方法,需要知道行號(hào),實(shí)踐中是不方便獲得的,下面是改進(jìn)的方法<script language="javascript">
var str;
</script><table ><tr onMouseDown="str=this.cells.item(0).innerText"><td>1行1列</td><td>1行2列</td></tr><tr onMouseDown="str=this.cells.item(0).innerText"><td>2行1列</td><td>2行2列</td></tr></table>當(dāng)鼠標(biāo)按下時(shí),我們就取到了該行第1列的值<td onMouseDown="str=this.innerText">2行1列</td>這可以取鼠標(biāo)所在列的值
無聊在電腦上亂點(diǎn).點(diǎn)出一個(gè)DWR的例子.于是乎開始學(xué)習(xí)DWR
拿出自己的練習(xí)曬下;
在做練習(xí)的時(shí)候遇到一個(gè)問題。web-inf下不生成classes文件夾,也不生成.class文件
經(jīng)過研究解決辦法為:右鍵點(diǎn)擊webmodule 選擇properties,再選擇Content,選擇Include All classes and resources 確定。OK
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee <display-name>WebModule1</display-name>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
dwr.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<!-- javascript的對(duì)象是jsmethodname,create="new"是DWR自己創(chuàng)建類 -->
<create javascript="jsmethodname" creator="new" scope="application">
<!-- value是java中的類名 -->
<param name="class" value="org.li.dwr.Hello"></param>
<!--<include>標(biāo)簽指定要公開給javascript的方法。不指定的話就公開所有方法。
<exclude>標(biāo)簽指定要防止被訪問的方法。-->
<include method="alertStr"/>
<include method="alertJSStr"/>
<include method="returnAl"/>
<include method="getList"/>
<include method="getObj"/>
</create>
<!--轉(zhuǎn)換java類型 -->
<convert converter="bean" match="org.li.dwr.InputRecord">
</convert>
</allow>
</dwr>
jsp頁面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DWR</title>
<meta http-equiv="content-type" content="text/html; charset=GBK">
<script type='text/javascript' src='dwr/interface/jsmethodname.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type="text/javascript" src="hello.js"></script>
<!--其中jsmethodname.js是dwr根據(jù)配置文件自動(dòng)生成的,engine.js和util.js是dwr自帶的腳本文件。
-->
</head>
<body>
<input id="jbutton" type="button" value="Hello World" onclick="jbClick()"/>
<div id="jdiv"></div>
<div id="jdiv2"></div>
<div id="uid"></div>
<div id="uname"></div>
<div id="usex"></div>
<div id="uaddress"></div>
</body>
</html>
js :hello.js
/*
function load()//載入的時(shí)候調(diào)用
{
var jbutton = document.getElementById("jbutton");
jbutton.onclick=function(event)//注冊(cè)按鈕點(diǎn)擊事件
{
jbClick();
};
}
*/
function jbClick()//按鈕點(diǎn)擊事件
{
// jshello.getHelloWorld(callback);//沒有參數(shù)傳遞,只傳遞回調(diào)函數(shù)就行
// jsmethodname.alertStr(callback1);//無參數(shù)
var data="js傳入java中的值";
// jsmethodname.alertJSStr(data,callback);//有參數(shù)。第一個(gè)為參數(shù),第二個(gè)為回調(diào)方法接收返回值
jsmethodname.getList(callbackList); //無參數(shù),返回list
//jsmethodname.getObj(callbackObj);
}
function callback1(msg)//回調(diào)函數(shù) ,調(diào)用java方法的javascript函數(shù)
{
//msg就是java方法的返回值
alert(msg);
}
function callback(msg)//回調(diào)函數(shù)
{
//這里可以進(jìn)行參數(shù)處理DWRUtil 的 setValue() 方法會(huì)將傳回的 msg 設(shè)定給指定 id 的 DOM
DWRUtil.setValue('jdiv',msg);
}
function callbackList(data){
for(var i=0;i<data.length;i++){
DWRUtil.setValue("uid", data[i].id);
DWRUtil.setValue("uname", data[i].name);
DWRUtil.setValue("usex", data[i].sex);
DWRUtil.setValue("uaddress", data[i].address);
}
}
function callbackObj(data){
//知道屬性
DWRUtil.setValue("uid", data.id);
DWRUtil.setValue("uname", data.name);
DWRUtil.setValue("usex", data.sex);
DWRUtil.setValue("uaddress", data.address);
/**
* 不知道屬性
for(var property in data){
//alert("property:"+property);
alert(property+":"+data[property]);
}
*/
}
java類
Hello.java
package org.li.dwr;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
public class Hello {
public String getHelloWorld() {
return "現(xiàn)在的時(shí)間為:" + new Date();
}
public String alertStr() {
return "DWR框架:無參數(shù)";
}
public String alertJSStr(String jsvalue) {
return "DWR框架:" + jsvalue;
}
public ArrayList returnAl() {
ArrayList al = new ArrayList();
al.set(1, "a");
al.set(2, "b");
al.set(3, "c");
al.set(4, "d");
return al;
}
public List getList() {
List list = new ArrayList();
for(int i=0;i<5;i++){
InputRecord ir = new InputRecord();
ir.setId(1);
ir.setName("依韻");
ir.setSex("男");
ir.setAddress("北京市");
list.add(ir);
}
return list;
}
public InputRecord getObj() {
InputRecord ir = new InputRecord();
ir.setId(2);
ir.setName("白色黃昏");
ir.setSex("女");
ir.setAddress("河南");
return ir;
}
}
InputRecord.java
package org.li.dwr;
public class InputRecord {
private int id;
private String name;
private String sex;
private String address;
public String getAddress() {
return address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setId(int id) {
this.id = id;
}
}