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

1.Flash遮罩问题:遮罩不了flash时候在FLASH里面属性
<param name="wmode" value="transparent"/>
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获取当前各种日期格式
<script language="javascript">
var myDate=new Date();   
document.write(myDate.getYear().toString()+"<br>");//获取当前年份(2位)   
document.write(myDate.getFullYear().toString()+"<br>");//获取当前完整的年份(4位,1970-????)
document.write(myDate.getMonth().toString()+"<br>");//获取当前月份(0-11,0代表1月)   
document.write(myDate.getDate().toString()+"<br>");//获取当前日(1-31)   
document.write(myDate.getDay().toString()+"<br>");//获取当前星期X(0-6,0代表星期天)   
document.write(myDate.getTime().toString()+"<br>");//获取当前时间(从1970-1-1开始的毫秒数)
document.write(myDate.getHours().toString()+"<br>");//获取当前小时数(0-23)   
document.write(myDate.getMinutes().toString()+"<br>");//获取当前分钟数(0-59)   
document.write(myDate.getSeconds().toString()+"<br>");//获取当前秒数(0-59)   
document.write(myDate.getMilliseconds().toString()+"<br>");//获取当前毫秒数(0-999)
document.write(myDate.toLocaleDateString().toString()+"<br>");//获取当前日期
</script>


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<ori.left-20||y<ori.top-20)box.style.display='none';
            x-=ori.left;
            y-=ori.top;
            box.style.left=x-z+'px';
            box.style.top=y-z+'px';
            img.style.left=-x*zoom+z+'px';
            img.style.top=-y*h+z+'px';
        }
        win.onmouseover=function (){box.style.display=''}
    }
};
function s(){
	
    	x=new zoomBox('shows','zoom');
}


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;
	}





你可能感兴趣的:(例子)