不用單點登錄,模擬遠程項目的登錄頁面表單,在訪問這個頁面的時候自動提交表單到此項目的登錄action,就可以實現登錄到其他系統。
ssh框架項目
1.以下是本地系統的action代碼:
1 import java.io.IOException; 2 import java.util.List; 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.URL; 8 import java.net.URLConnection; 9 10 public class myLoginAction { 11 12 /** 13 * 查詢是否用戶已注冊 14 * @return 15 * @throws Exception 16 */ 17 public void checkUser() throws Exception{ 18 Loginer loginer = (Loginer) request.getSession() 19 .getAttribute("loginer"); 20 21 String url = "http://www.youtest.com/login.php"; //遠程系統登錄action地址 22 String param = "username=Tom&password=123456"; //參數 23 String temp = "alert('用戶名或密碼錯誤');"; //返回的信息,此處是錯誤信息,用於比較。 視情況而定 24 boolean result =false ; 25 //驗證數據是否能登錄 26 result = sendPost(url, param, temp); 27 if(result){ 28 return "login"; 29 }else{ 30 return "register"; 31 } 32 } 33 34 //訪問遠程登錄action並獲取返回的信息 35 public static boolean sendPost(String url, String param, String temp) { 36 PrintWriter out = null; 37 BufferedReader in = null; 38 boolean result = true; 39 try { 40 URL realUrl = new URL(url); 41 // 打開和URL之間的連接 42 URLConnection conn = realUrl.openConnection(); 43 // 設置通用的請求屬性 44 conn.setRequestProperty("accept", "*/*"); 45 conn.setRequestProperty("connection", "Keep-Alive"); 46 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 47 // 發送POST請求必須設置如下兩行 48 conn.setDoOutput(true); 49 conn.setDoInput(true); 50 // 獲取URLConnection對象對應的輸出流 51 out = new PrintWriter(conn.getOutputStream()); 52 // 發送請求參數 53 out.print(param); 54 // flush輸出流的緩沖 55 out.flush(); 56 // 定義BufferedReader輸入流來讀取URL的響應 57 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); 58 String line; 59 while ((line = in.readLine()) != null) { 60 if(temp.equals((line.trim()))) { 61 System.out.println("錯誤的line:"+line); 62 result = false; 63 } 64 } 65 } catch (Exception e) { 66 result = false; 67 logger.error("發送 POST 請求出現異常!"+e); 68 System.out.println("發送 POST 請求出現異常!"+e); 69 e.printStackTrace(); 70 }finally{ 71 try{ 72 if(out!=null){ 73 out.close(); 74 } 75 if(in!=null){ 76 in.close(); 77 } 78 }catch(IOException ex){ 79 logger.error(ex); 80 ex.printStackTrace(); 81 } 82 } 83 return result; 84 } 85 }
2.模擬的登錄頁面:
1 <html> 2 <head></head> 3 <body> 4 <script type="text/javascript"> 5 var iframe = document.createElement("iframe"); 6 iframe.src = "http://www.youtest.com/login.php?UNAME=<%=userName%>&UPWD=<%=pwd%>"; 7 iframe.style.display="none"; 8 9 var sta="false;" 10 if (iframe.attachEvent){ 11 iframe.attachEvent("onload", function(){ 12 window.location.href="http://www.youtest.com/index.html"; 13 }); 14 } else { 15 iframe.onload = function(){ 16 window.location.href="http://www.youtest.com/index.html"; 17 }; 18 } 19 document.body.appendChild(iframe); 20 </script> 21 </body> 22 </html>