顯示具有 JSP 標籤的文章。 顯示所有文章
顯示具有 JSP 標籤的文章。 顯示所有文章

2011年9月19日 星期一

How to detect a visitor's IP address

Every visitor to your site or web application has an IP address. It is quite handy to be able to get that address. It can be used for security logging, or perhaps tracing. It can also be used to determine where they are in the world, or at least where their ISP is.
The difficulty is when they're behind a proxy of some sort, you only see the IP address of the proxy server. So, here are the code snippets in PHP,JSP, ASP and .Net that first check for an IP addresses that's forwarded from behind a proxy, and if there's none then just get the IP address.
  • PHP without Proxy detection
    <? $ipaddress = getenv(REMOTE_ADDR); ?>
  • PHP with Proxy detection
    <?if (getenv(HTTP_X_FORWARDED_FOR)) {
    $ipaddress = getenv(HTTP_X_FORWARDED_FOR);
    } else {
    $ipaddress = getenv(REMOTE_ADDR); }
    ?>
  • ASP without Proxy detection
    <%
    ipaddress = Request.ServerVariables("REMOTE_ADDR")
    %>
  • ASP with Proxy detection
    <%
    ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    if ipaddress = "" then
    ipaddress = Request.ServerVariables("REMOTE_ADDR")
    end if
    %>
  • JSP without Proxy detection
    <%
    String ipaddress = request.getRemoteAddr();
    %>
  • JSP with Proxy detection
    <%
    if (request.getHeader("HTTP_X_FORWARDED_FOR") == null) {
    String ipaddress = request.getRemoteAddr();
    } else {
    String ipaddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    %>
我想了解如何获得IP地址的客户端,即访问我的网页。
内容的JSP页面:
<%  
out.print( request.getRemoteAddr() + "<br>"); 
out.print( request.getRemoteHost() );  
%> 
输出:
0:0:0:0:0:0:0:1 
0:0:0:0:0:0:0:1 

2011年9月15日 星期四

JSP – Fetching Value of Radio Button

JSP – Fetching Value of Radio Button

Radio button in JSP with same name return a single value to request object. Request.getParameter with radio field name will return a value of checked radio button.
Suppose we have three radio button and name of radioButton, if we select b value radio button, and submit this JSP page to getValue.jsp page. We will get value of request object is b. index.jsp

<html>
<head>
<title>Radio Button</title>

</head>

<body>
<form name="frm" action="getValue.jsp" method="post" >
<input name="radioButton" type="radio" value="a" checked="checked"/> a
<input name="radioButton" type="radio" value="b" /> b
<input name="radioButton" type="radio" value="c" /> c
<input name="goto" type="submit" value="Submit" />
</form>
</body>
</html>
Fetching request value in this page of radio button
getValue.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
 String radioButton= request.getParameter("radioButton");
 System.out.println("radioButton ::"+radioButton);
 out.println("Radio Button Value :"+radioButton);
%>

2011年9月13日 星期二

產生驗證碼圖片的文件

------------產生驗證碼圖片的文件-----image.jsp-------------------------------------------
<%@ page contentType="image/jpeg" 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=60, height=20;
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,18));
//畫邊框
//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(12);
        int yl = random.nextInt(12);
 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,13*i+6,16);
}
// 將認證碼存入SESSION
session.setAttribute("rand",sRand);
// 圖像生效
g.dispose();
// 輸出圖像到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
---------------使用驗證碼圖片的文件---------a.jsp------------------------------------
<%@ page contentType="text/html;charset=gb2312" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>認證碼輸入頁面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
</head>
<body>
<form method=post action="check.jsp">
<table>
<tr>
<td align=left>系統產生的認證碼:</td>
<td><img border=0 src="image.jsp"></td>
</tr>
<tr>
<td align=left>輸入上面的認證碼:</td>
<td><input type=text name=rand maxlength=4 value=""></td>
</tr>
<tr>
<td colspan=2 align=center><input type=submit value="提交檢測"></td>
</tr>
</form>
</body>
</html>
-----------------驗證的頁面----------check.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>認證碼驗證頁面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
</head>
<body>
<%
 String rand = (String)session.getAttribute("rand");
 String input = request.getParameter("rand");
%>
系統產生的認證碼為: <%= rand %><br>
您輸入的認證碼為: <%= input %><br>
<br>
<%
  if (rand.equals(input)) {
%>
<font color=green>輸入相同,認證成功!</font>
<%
  } else {
%>
<font color=red>輸入不同,認證失敗!</font>
<%
  }
%>
</body>
</html>

2011年9月5日 星期一

透過HttpWebRequest類別POST編碼為Big5的資料到其他網站接收

最近遇到一個問題是要透過HttpWebRequest類別採post的方式將原本unicode的資料轉成big5編碼方式送出給遠端的Server,遠端Server會將接收到的欄位值發送簡訊至手機上。因為遠端Server的接收頁面採用Big5的編碼,且字串資料一律接使用Big5來處理。原本以為很簡單的只要將要處理的字串透過編碼轉換的方式轉成Big5後,就可以直接Post出去給遠端Server即可,但是發現遠端Server卻是一直接收到utf-8傳來亂碼,導致發送出來的簡訊都是亂碼。
後來參考保哥文章"關於個瀏覽器對網頁與文字編碼的處理規則研究整理"一文,以及另外一篇網路文章"C#, 使用 HttpWebRequest 向網站提交資料",終於把惱人的亂碼問題給解決掉。其實會一直失敗的原因主要是因為透過WebRequest.Create(requestUriString)時,requestUriString必須將字串進行UrlEncode為Big5碼的動作才行。
以下是自己的Post Big5碼資料的Method供參考
01/// <SUMMARY>
02/// This method is used to post data to remote host via WebRequest
03/// </SUMMARY>
04/// 
05private void postFormViaWebRequest(Dictionary<STRING,STRING> inpufFileds, string sendURL)
06{
07    Encoding encoding = Encoding.GetEncoding(950);
08    string postData = string.Empty;
09    foreach (KeyValuePair<STRING,STRING> kvp in inpufFileds)
10    {
11        postData += "&" + HttpUtility.UrlEncode(kvp.Key, encoding) + "=" + HttpUtility.UrlEncode(kvp.Value, encoding);
12    }
13    byte[] data = Encoding.ASCII.GetBytes(postData);
14    HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(sendURL + "?");
15    postRequest.Method = "POST";
16    postRequest.ContentType = "application/x-www-form-urlencoded;charset=big5";
17    postRequest.ContentLength = data.Length;
18    Stream requestStream = postRequest.GetRequestStream();
19    requestStream.Write(data, 0, data.Length);
20    requestStream.Close();
21}</STRING,STRING></STRING,STRING>

2011年9月4日 星期日

URLRequest物件有一個manageCookie可以設定為true


關於URLRequest物件有一個manageCookie可以設定為true試試,
屬性的說明網頁如下:
看說明大概是在windows一定要設定true才會自動管理,
不過預設值其實就是true了,
但你還是可以設定為true試試,
看是不是有把request的cookie自動附加上去,
如果不行其實個人覺得最簡單的方法就是用flash呼叫javascript做導頁是最簡單的@@”,
基本上大概加個幾行應該就可以達到此目的,

JSP Cookie的使用

JSP Cookie的使用
Cookie是在Client端留下的資訊,一般新增一個Cookie是使用如下的方式

Cookie ck = new Cookie(索引值, 資料內容);
response.addCookie(ck);

而Cookie的取出,則是使用如下的方式
  Cookie ck[] = request.getCookies();
  int i;
  for(i=0;i<ck.length;i++) {
     out.print("ck.name="+ck[i].getName());
     out.print(" value=" + ck[i].getValue()+"<BR>");

Cookie.getName() 便是取得當時Cookie存入時的 索引值
Cookie.getValue() 便是取得當時Cookie存入時的 資料內容
而Cookie的取出沒有他法,全都只能使用以下方式,把所有Cookie都讀出
Cookie ck[] = request.getCookies();

而Cookie的生命週期有多長,是由Cookie 名稱.setMaxAge(秒數)來設定,如果沒有設定之,則Cookie會在Browser結束掉時結束。如果設定秒數=3600,代表該Cookie可以由設定的時間算起,活3600秒(1小時),就算Browser結束掉後再進來,只要在一小時之內,都可以讀取到該Data。但若設為0,代表要刪除該Cookie。

Cookie是server傳送給瀏覽器一段資訊(都是文字,且中間不能有空白),瀏覽器收到cookie後會將其儲存起
來,之後每次讀取這部server上的網頁時,就根據一些規則把以前收到cookie傳給server。但Cookie使用
上需依賴client是否有接受cookie的設定限制。傳送到客戶端的Cookie物件,可不限一個,如果有多個Cookie
物件要傳送的話,可以連續執行addCookie(),把所有的Cookie都加至response物件,一次將所有Cookie都送
至對方的瀏覽器內。

Cookie可以透過c.setMaxAge()函式來設定有效時間,如果c.setMaxAge()內的參數是一個正整數值,
則單位就是以秒來計算,數值越大則Cookie物件的有效的時間越久,若參數值為0,則表示Cookie物
件存放在瀏覽器後將立即失效,若參數為負整數值時,則當瀏覽器被關閉後,此此Cookie物件也馬上
失效

然而,若兩個不同的網站都使用Cookie,而索引值也相同,但內容不同時,後面網站的設定會OverWrite前面網站的設定嗎?答案是不會,我們可以在Window的根目錄(如:C:\Windows或C:\WinNt )下找一個Cookies的Directory,該Directory內的資料便是Cookies存放的地方,不同的網站會把Cookies存在不同的File之中,所以沒有這OverWrite的問題。

Cookie.jsp
<HTML>
<HEAD>

<TITLE>
Jsp2
</TITLE>
</HEAD>
<BODY>
<%
Cookie ck = new Cookie("cww2","test2!!");
ck.setMaxAge(65536);
response.addCookie(ck);
%>
</BODY>
</HTML>

GetCookie 之範例
<HTML>
<HEAD>
<TITLE>
getcookie
</TITLE>
</HEAD>
<BODY>
<H1>
JBuilder Generated JSP
</H1>
<%
  Cookie ck[] = request.getCookies();
  int i;
  for(i=0;i<ck.length;i++) {
     out.print("ck.name="+ck[i].getName());
     out.print(" value=" + ck[i].getValue()+"<BR>");
  }

%>
ok
</BODY>

Session是某段時間內一連串客戶端與伺服端的talking,這連線會一直持續到某個時間後,不再向
Web要求.jsp網頁時才結束(即timeout)或者使用session.invalidate()。一個session可能包含一個使用者
的多個請求(request)。

因為http不具有狀態,所以若需要保持使用狀態,就需要cookie或session。但是session可能會timeout,
而cookie可能被disable,所以有時得用隱藏欄位來做事情。

每一個客戶端都對應著一個session物件用來存放與這個客戶端相關的交易資料,而存放在這個
session物件內的資料,可以是複雜的物件型態,並非單純的文字。

通常在JSP程式中,不需要特別寫任何程式就可取用session物件,但也可在JSP程式中加入
<%@ page session=“true”%>,表示session功能已啟動,若設為false時,代表要關閉session功能。

session.isNew()是一boolean
    若傳回值為true,代表為第一次被建立使用,若為false則代表為正在被使用中。
session.getMaxInactiveInterval()   此一函式是用來讀取此一session的有效期限。
session.setMaxInactiveInterval(1800) 表示設定session的有效期限,參數型態為整數,單位為秒。
session.getAttribute(String name)   取得指定索引鍵中的值,參數型態為字串,表索引鍵名,
                  傳回值為一object型態,必須透過轉型才能轉換成正確的類別型態。
session.putAttribute(String name,Object Value)
        session的存放格式如cookie一樣,是為“索引值(key)=值(value)” ,但存入值的型態為物件
        型態,第一參數為索引鍵,第二為要存入session的物件。
session.removeAttribute(String name)
     移除session物件中不需再使用的索引鍵,參數為字串型態,代表要移除的索引鍵。
session.getId()   取得session的識別資訊
session.getValueNames()    傳回所有存放在session物件中的索引鍵名
session.invalidate()  中斷session
session.getLastAccessedTime() 傳回long表示離1970/1/1 00:00:00最後access的毫秒數
session.getCreationTime() 回long表示離1970/1/1 00:00:00 create的毫秒數