记录一些不常用但又比较好例子

阅读更多
1.Flash遮罩问题:遮罩不了flash时候在FLASH里面属性

2.改变鼠标样式(CSS)
cursor:url('left.cur'),url('left.cur'), default;
3.添加事件 (JS)
setAttribute("onclick", "javascript:comeback();");
4.将中文转换为UTF-8的URL编码方法。
 public static String utf(String s){
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < s.length(); i++) {
	            char c = s.charAt(i);
	            if (c >= 0 && c <= 255) {
	                sb.append(c);
	            } else {
	                byte[] b;
	                try {
	                    b = String.valueOf(c).getBytes("utf-8");
	                } catch (Exception ex) {
	                    System.out.println(ex);
	                    b = new byte[0];
	                }
	                for (int j = 0; j < b.length; j++) {
	                    int k = b[j];
	                    if (k < 0)
	                        k += 256;
	                    sb.append("%" + Integer.toHexString(k).toUpperCase());
	                }
	            }
	        }
	        return sb.toString();
	    }

5.访问一个网站地址将他输出.

public void pintWeb(){
		 /** 读入输入流的数据长度 */
        int chByte = 0;
        /** 网络的url地址 */
        URL url = null;
        /** http连接 */
        HttpURLConnection httpConn = null;
        /** 输入流 */
        BufferedReader br=null;
        /** 文件输出流 */
        try{
            url = new URL("http://10.10.0.58/");
            httpConn = (HttpURLConnection) url.openConnection();
            HttpURLConnection.setFollowRedirects(true);
            httpConn.setRequestMethod("POST"); 
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); 
            br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
            HttpServletResponse response = ServletActionContext.getResponse();
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
            	response.getWriter().print(inputLine);
            }
            response.getWriter().print((char)chByte);
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        finally{
            try{
                br.close();
                httpConn.disconnect();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
	}


6.设置节点的透明度CSS.
filter:alpha(opacity=20);-moz-opacity:0.2;-khtml-opacity: 0.2; opacity: 02;

7.改变图片大小方法
需要手动引入
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
(可能会在未来版本中删除)
public void imageScale(String srcFilePath, String targetFilePath,int width, int height) {  
		this.imageScale("原始图片路径","转换图片的路径", 宽, 高);  
	}  
	public void imageScale(File srcFile, File targetFile, int width, int height) {  
		try {
			Image image = javax.imageio.ImageIO.read(srcFile);  
			image = image.getScaledInstance(width, height,Image.SCALE_AREA_AVERAGING); 
			BufferedImage mBufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
			Graphics2D g2 = mBufferedImage.createGraphics();              
			g2.drawImage(image, 0, 0, width, height, Color.white, null);  
			g2.dispose();  
			float[] kernelData2 = { -0.125f, -0.125f, -0.125f, -0.125f, 2,-0.125f, -0.125f, -0.125f, -0.125f };  
			Kernel kernel = new Kernel(3, 3, kernelData2);  
			ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);  
			mBufferedImage = cOp.filter(mBufferedImage, null);  
			File targetDir = targetFile.getParentFile();  
			if (!targetDir.exists())  
				targetDir.mkdirs();  
			FileOutputStream out = new FileOutputStream(targetFile);  
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
			encoder.encode(mBufferedImage);  
			out.close();  
		} catch (Exception e) {  
			e.printStackTrace();
		}  
	}




8.JS获取当前各种日期格式



9.原始JS的放大镜
function zoomBox() {this.index.apply(this, arguments)}
zoomBox.prototype = {
    index: function(win,zoom) {
		//获得图片窗体
        var win=document.getElementById(win);
		//获得放大镜窗体
        var box=document.getElementById(zoom);
		
		//获得放大镜图片
        var img=box.getElementsByTagName('IMG')[0];
		//放大镜图片的宽度除以浏览图片的宽度
        var zoom=img.width/win.getElementsByTagName('IMG')[0].width;
		var h=img.height/win.getElementsByTagName('IMG')[0].height;
		//随机数
	
        var z=Math.round(box.offsetWidth/2);
        win.onmousemove=function (e){
            e = e || window.event;
            var x=e.clientX,y=e.clientY, ori=win.getBoundingClientRect();
            if (x>ori.right+20||y>ori.bottom+20||x 
 

10.字符串转日期

Date dad=new Date("Thu Apr 05 11:30:39 CST 2012");
		SimpleDateFormat simpe=new SimpleDateFormat("yyyy-mm-dd");
		System.out.println(simpe.format(dad));


11.下载

String   filepath   =  (String)request.getAttribute("out");
	String filename=filepath.split("\\\\")[1];
	ServletOutputStream  out1=response.getOutputStream(); 
    //   得到文件名字和路径 
    //   设置响应头和下载保存的文件名 
    response.setContentType( "APPLICATION/PDF"); 
    response.setHeader( "Content-Disposition","filename="+filename); 
    //   打开指定文件的流信息 
    java.io.FileInputStream   fileInputStream   =  new java.io.FileInputStream(filepath); 
    //   写出流信息 
    int   i; 
    while((i=fileInputStream.read())!=-1)   { 
      out1.write(i); 
    } 
    fileInputStream.close(); 
    out1.close(); 




12.加密解密
/**
	 * 加密字符串
	 */
	public static String ebotongEncrypto(String str) {
		String result = str;
		if (str != null && str.length() > 0) {
			try {
				byte[] encodeByte = symmetricEncrypto(str.getBytes(encoding));
				result = base64encoder.encode(encodeByte);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 对称加密方法
	 * 
	 * @param byteSource
	 *            需要加密的数据
	 * @return 经过加密的数据
	 * @throws Exception
	 */
	public static byte[] symmetricEncrypto(byte[] byteSource) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			int mode = Cipher.ENCRYPT_MODE;
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			byte[] keyData = { 1, 9, 8, 2, 0, 8, 2, 1 };
			DESKeySpec keySpec = new DESKeySpec(keyData);
			Key key = keyFactory.generateSecret(keySpec);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(mode, key);
			byte[] result = cipher.doFinal(byteSource);
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			baos.close();
		}
	}

	/**
	 * 对称解密方法
	 * 
	 * @param byteSource
	 *            需要解密的数据
	 * @return 经过解密的数据
	 * @throws Exception
	 */
	public static byte[] symmetricDecrypto(byte[] byteSource) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			int mode = Cipher.DECRYPT_MODE;
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			byte[] keyData = { 1, 9, 8, 2, 0, 8, 2, 1 };
			DESKeySpec keySpec = new DESKeySpec(keyData);
			Key key = keyFactory.generateSecret(keySpec);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(mode, key);
			byte[] result = cipher.doFinal(byteSource);
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			baos.close();
		}
	}
	
	/**
	 * 解密字符串
	 */
	public static String ebotongDecrypto(String str) {
		String result = str;
		if (str != null && str.length() > 0) {
			try {
				byte[] encodeByte = base64decoder.decodeBuffer(str);
				byte[] decoder = CommonUtils.symmetricDecrypto(encodeByte);
				result = new String(decoder, encoding);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}



用正则表达式获取数据 替换数据



String hrefs = "asdfsdsdf{dd}dsdfasdfasdf";
				Pattern p = Pattern.compile("\\{(.*?)\\}");
			    Matcher m = p.matcher(hrefs);
				String key = "";
			    while(m.find()) {
			    	key = m.group(1);
			    	hrefs = newHref.replaceAll("(\\{["+key+"\\}]+})", map.get(key).toString());
			    }


注入属性

public static Object InjectionValue(Object object,ScrollableResults srs){
		//获取DTO模板
		Class classes = object.getClass();
		//获取字段组
		Field[] fieldlist = classes.getDeclaredFields();
		try{
			 for (int i = 0; i < fieldlist.length; i++){
				Field fld = fieldlist[i];
				//拼接set属性方法
		        StringBuffer name = new StringBuffer();
		        name.append("set");
		    	name.append(fld.getName().substring(0,1).toUpperCase());
		    	name.append(fld.getName().substring(1));
		    	//获取DTO set方法
		        Method method = classes.getMethod(name.toString(),new Class[] {fld.getType()});
		        //拼接srs的get方法
		        StringBuffer name2 = new StringBuffer();
		        int length = fld.getType().toString().split("[.]").length;
		        String methodName = fld.getType().toString().split("[.]")[length-1];
		        name2.append("get");
		    	name2.append(methodName);
		    	//获取ScrollableResults的get方法
		        Method srsMethod = srs.getClass().getMethod(name2.toString(), new Class[] {int.class});
		        //注入值
		        method.invoke(object,srsMethod.invoke(srs, i));
		    }
		}catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}





Spring 的类型转换器

DefaultConversionService conversionService = new DefaultConversionService();  
		Integer i = conversionService.convert("5", Integer.class);  
		System.out.println(i.getClass().getName());




js数组元素的添加和删除一直比较迷惑,今天终于找到详细说明的资料了,先给个我测试的代码^-^
var arr = new Array();
arr[0] = "aaa";
arr[1] = "bbb";
arr[2] = "ccc";
//alert(arr.length);//3
arr.pop();
//alert(arr.length);//2
//alert(arr[arr.length-1]);//bbb
arr.pop();
//alert(arr[arr.length-1]);//aaa
//alert(arr.length);//1

var arr2 = new Array();
//alert(arr2.length);//0
arr2[0] = "aaa";
arr2[1] = "bbb";
//alert(arr2.length);//2
arr2.pop();
//alert(arr2.length);//1
arr2 = arr2.slice(0,arr2.length-1); 
//alert(arr2.length);//0
arr2[0] = "aaa";
arr2[1] = "bbb";
arr2[2] = "ccc";
arr2 = arr2.slice(0,1); 
alert(arr2.length);//1
alert(arr2[0]);//aaa
alert(arr2[1]);//undefined

shift:删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined 
var a = [1,2,3,4,5]; 
var b = a.shift(); //a:[2,3,4,5]   b:1 

unshift:将参数添加到原数组开头,并返回数组的长度 
var a = [1,2,3,4,5]; 
var b = a.unshift(-2,-1); //a:[-2,-1,1,2,3,4,5]   b:7 
注:在IE6.0下测试返回值总为undefined,FF2.0下测试返回值为7,所以这个方法的返回值不可靠,需要用返回值时可用splice代替本方法来使用。 

pop:删除原数组最后一项,并返回删除元素的值;如果数组为空则返回undefined 
var a = [1,2,3,4,5]; 
var b = a.pop(); //a:[1,2,3,4]   b:5 //不用返回的话直接调用就可以了

push:将参数添加到原数组末尾,并返回数组的长度 
var a = [1,2,3,4,5]; 
var b = a.push(6,7); //a:[1,2,3,4,5,6,7]   b:7 

concat:返回一个新数组,是将参数添加到原数组中构成的 
var a = [1,2,3,4,5]; 
var b = a.concat(6,7); //a:[1,2,3,4,5]   b:[1,2,3,4,5,6,7] 

splice(start,deleteCount,val1,val2,...):从start位置开始删除deleteCount项,并从该位置起插入val1,val2,... 
var a = [1,2,3,4,5]; 
var b = a.splice(2,2,7,8,9); //a:[1,2,7,8,9,5]   b:[3,4] 
var b = a.splice(0,1); //同shift 
a.splice(0,0,-2,-1); var b = a.length; //同unshift 
var b = a.splice(a.length-1,1); //同pop 
a.splice(a.length,0,6,7); var b = a.length; //同push 

reverse:将数组反序 
var a = [1,2,3,4,5]; 
var b = a.reverse(); //a:[5,4,3,2,1]   b:[5,4,3,2,1] 

sort(orderfunction):按指定的参数对数组进行排序 
var a = [1,2,3,4,5]; 
var b = a.sort(); //a:[1,2,3,4,5]   b:[1,2,3,4,5] 

slice(start,end):返回从原数组中指定开始下标到结束下标之间的项组成的新数组 
var a = [1,2,3,4,5]; 
var b = a.slice(2,5); //a:[1,2,3,4,5]   b:[3,4,5] 

join(separator):将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符 
var a = [1,2,3,4,5]; 
var b = a.join("|"); //a:[1,2,3,4,5]   b:"1|2|3|4|5"

再给个利用数组模拟javaStringBuffer处理字符串的方法:

/**
* 字符串处理函数
*/
function StringBuffer()
{
var arr = new Array;
this.append = function(str)
{
    arr[arr.length] = str; 
};

this.toString = function()
{
    return arr.join(""); //把append进来的数组ping成一个字符串
};
}

今天在应用中突然发现join是一种把数组转换成字符串的好方法,故封装成对象使用了:

/**
* 把数组转换成特定符号分割的字符串
*/
function arrayToString(arr,separator)
{
if(!separator) separator = "";//separator为null则默认为空
    return arr.join(separator); 
}

/**
* 查找数组包含的字符串
*/
function arrayFindString(arr,string)
{
var str = arr.join(""); 
    return str.indexOf(string); 
}


Eclipse 改变 包样式
包括Object.class.getResourceAsStream 为null 情况可以加载里面
**/*.java

你可能感兴趣的:(java,javascript)