2008年6月17日 星期二

[JavaScript]完整保存TextArea的文字

這個主要是在textarea內給人填html語法, submit過後好幾頁還需要預覽那個html語法...
因為裡面會有換行, <>, ", ', \, 這堆跳脫字元...
要去加字也不對...
因為之後直接取出來不能用...
後來有Javascript大師提供的...偷吃步XD"...

提示: 用div包起來, 不要顯示

< div id="noDisplay" style="display:none">
<%out.print(session.getAttribute("html_text"));%>
< /div>

javascript:
document.getElementById('preview').innerHTML = document.getElementById('noDisplay').innerHTML;

\囧/ 想一想這個真是有夠神奇的偷吃步...

[JSP/JavaScript]圖片檢查碼

再來這個就高深了XD...
還好有同事的sample code可以拿來參考修改...
不過真的寫好到套上去可以用也是花了一天的功夫...

<%@ page contentType="image/jpeg" language="java" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>


Color getRandColor(int fc,int bc){//給定範圍獲得隨機顏色
Random random = new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
return new Color(r,g,b);
}
//設置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
// 在內存中創建圖像
int width=200, height=50, fontSize=45;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取圖形上下文
Graphics g = image.getGraphics();
//生成隨機類
Random random = new Random();
// 設定背景色
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
//設定字體
g.setFont(new Font("Times New Roman",Font.PLAIN,fontSize));
//畫邊框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);

// 隨機產生155條干擾線,使圖像中的認證碼不易被其它程序探測到
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(20);
int yl = random.nextInt(20);
g.drawLine(x,y,x+xl,y+yl);
}
// 取隨機產生的認證碼(4位數字)
String sRand="";
for (int i=0;i<4;i++) {
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
// 將認證碼顯示到圖像中
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); //調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
g.drawString(rand,fontSize*i+random.nextInt(15),height-random.nextInt(15));
}
// 將認證碼存入SESSION
session.setAttribute("rand",sRand);
// 圖像生效
g.dispose();
// 輸出圖像到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();

裡面是把產生出來的碼存在seesion中, 所以檢核一定要submit到下一頁時才能檢查...

另外一個問題是"重新產生檢查碼"...因為jsp要被reload才會變更數字...
但是整個jsp頁面reload就很搞笑, 而且還要記頁面一堆有的沒的資料...
所以這時候就需要一個萬能的iframe~
< iframe frameborder="0" allowtransparency=true src="./ooxx.html" style="width:400px;height:85px;border:0px;cellpadding:0px;cellspacing:0px" / >

ooxx.html裡面主要就是含圖跟變更檢查碼
< img border="0" id="img_safe_code" src="./image.jsp" / >
< a href="#" class="ps style7" onclick="document.forms[0].submit();">重新產生安全碼< / a >

[JSP/JavaScript]檔案上傳

主要是利用 apache的 fileUpload...

首先要先設定前一頁submit的form型態為multipart, 而且只能使用POST method
< form name="b4page" id="b4page_info" method="POST" enctype="multipart/form-data" >

再來是submit下一頁後的jsp, 用fileUpload寫檔到server端的某一位置

<%@page import="org.apache.commons.io.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, org.apache.commons.fileupload.servlet.*, java.io.*, java.util.*"%>

//upload file
boolean isUpload = false;
String foldar = "../tempImg/";
int MaxMemorySize = 1024*1024*100;
int limitFileSize = 5;

ServletFileUpload upload = null;
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(MaxMemorySize);
// Create a new file upload handler
upload = new ServletFileUpload(factory);
} catch(Exception e) { }

if(upload != null && upload.isMultipartContent(request)) {
isUpload = true;
}
if(isUpload) {
String key = (String)session.getAttribute("pic_key");
if(key == null) {
session.setAttribute("pic_key", String.valueOf(System.currentTimeMillis()));
key = (String)session.getAttribute("pic_key");
}

try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
FileItem imgFile = null;
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//System.out.println("??item name="+item.getFieldName()+", "+item.isFormField());
if (item.isFormField()) { //此處取得的就是一般正常的param(text, hidden, select ...etc)
String fieldName = item.getFieldName();
String value = item.getString("UTF-8");
} else {
imgFile = item;
}
}

if(imgFile != null) {
String fieldName = imgFile.getFieldName();
String fileName = imgFile.getName();
String contentType = imgFile.getContentType();
boolean isInMemory = imgFile.isInMemory();
long sizeInBytes = imgFile.getSize();
if(sizeInBytes>1024*1024*limitFileSize) {
errMsg = "圖檔檔案過大(限制"+limitFileSize+" MB.), 請回上一頁重新上傳!!";
}

if(sizeInBytes>0){
String fname = key+fileName.substring(fileName.lastIndexOf("."));
// 先放在tmp裡!
File f = new File( foldar, fname );
//System.out.println("Upload File Path:"+f.getAbsolutePath());
imgFile.write(f);
//System.out.println("Upload File complete!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}


大概要比較注意的是, multipart傳上去的東西, getParameter這個method就get不到東西了...
要從isFormField那邊取得

[JSP/Java]讀取https的網頁

一般讀網頁就是用URL...但是有時候碰到的機車事就是要讀https...
最近都用JSP在寫, 主要的好處是不用重起server就可以運行...
搭載功能上速度跟要修改可以快很多~

以下截取重點:

<%@page import="java.net.*, java.io.*, javax.net.ssl.*" %>

TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e3) { }


StringBuffer theURL = new StringBuffer();

//System.out.println(theURL.toString());
URL url = new URL(theURL.toString());
//url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
while(br.ready()) {
String tmp2 = br.readLine();
}

---------------------------------------------------
後記...在爬文章時~ 看到了這一篇
http://ws.apache.org/xmlrpc/ssl.html
被說成是 "The quick and dirty solution"...XD
偶也知道正規要去弄keystore...可是那很麻煩阿~囧rz...
有時候被迫在一個無法掌握SERVER重啟運作的情況下的快解...
不過正規的也是要懂一下啦Q_Q...