SWING实现新浪微博客户端(1)自动登录功能

最近在做一些,基于浏览器的应用整合项目。使用到了DJNative (一种JAVA浏览器实现http://sourceforge.net/projects/djproject/files/DJ%20Native%20Swing/0.9.9%20preview/DJNativeSwing-SWT-0-9-9-20110224.zip/download),对于一些进行接口开发的业务整合系统,提供了一种不错的思路。周末兴趣所致,写了一个新浪微博自动登录的例子。
实现一下功能:1,如果已经登录过的用户,读取配置文件中的用户名密码,调用当前页面自动完成登录。
2,如果未登录用户提示用户输入用户名密码,在用户登录成功后自动截取用户名密码保存到配置文件。
3,当用户名密码出错时清楚已保存的用户名密码,提示用户重新登录。

第一次运行时 提示没有从配置文件中读取到用户名密码

 

写道
class SsoListener extends WebBrowserAdapter{
public void locationChanged(WebBrowserNavigationEvent e) {
if (e.getNewResourceLocation().equals("http://t.sina.com.cn/")){
String loginname= userProperties.getProperty("loginname") ;
String password= userProperties.getProperty("password") ;
if ((loginname!=null &&!loginname.equals("")) && (password!=null && !loginname.equals(""))){
String script="document.getElementById('loginname').value='"+loginname+"';" +LS+
"document.getElementById('password').value='"+password+"';" +LS+
"document.getElementById('login_submit_btn').click();";
e.getWebBrowser().executeJavascript(script);
}else{
String script="function saveuser(){" +LS+
"sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+

"}" +LS+
"document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+
"alert('存储的用户名密码为空,请输入用户名密码')" +LS+
"";
e.getWebBrowser().executeJavascript(script);
e.getWebBrowser().removeWebBrowserListener(this);
e.getWebBrowser().addWebBrowserListener(new ReLoginListener());

}

}else{
System.out.println(e.getNewResourceLocation());
}
}
}

 
第一次登录提示没有获取到配置文件中的用户

 

 

输入用户名密码:

 

输入用户名密码:


输入用户名密码成功:成功登录


这时已将用户名密码保存到userProperties.properties中

 

再次运行时将自动完成新浪微博的登录!

完整的代码如下:

 

import java.awt.BorderLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.swing.BorderFactory;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserCommandEvent;

import chrriis.dj.nativeswing.swtimpl.components.WebBrowserNavigationEvent;





public class SSOSina extends JPanel {

  protected static final String LS = System.getProperty("line.separator");
   private static final  String  loginUrl="http://t.sina.com.cn";
   
   private static  Properties  userProperties=new Properties();
	
  public SSOSina() {
    super(new BorderLayout());
    
    InputStream in = this.getClass().getResourceAsStream("userProperties.properties");
    if (in == null) {
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream("userProperties.properties");
        if (in == null) {
            in = this.getClass().getClassLoader().getResourceAsStream("userProperties.properties");
        }
    }
    
    try {
		userProperties.load(in);
	} catch (IOException e1) {
		e1.printStackTrace();
	}
    
    JPanel webBrowserPanel = new JPanel(new BorderLayout());
    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("DJNative JAVA浏览器实现 实现新浪微博自动登录"));
    final JWebBrowser webBrowser = new JWebBrowser();
    webBrowser.setBarsVisible(true);
    webBrowser.setDefaultPopupMenuRegistered(true);
    webBrowser.setStatusBarVisible(true);
   
    webBrowser.navigate(loginUrl);
    //单点登录自动提交监听器
    class SaveUserListener extends WebBrowserAdapter{
    	   @Override
           public void commandReceived(WebBrowserCommandEvent e) {
             String command = e.getCommand();
             Object[] parameters = e.getParameters();
             if("print".equals(command)) {
               String html = (String)parameters[0] ;
               System.out.println(html);
             }
             if("saveuser".equals(command)) {
           	    String loginname = (String)parameters[0] ;
           	    String password = (String)parameters[1] ;
           	 userProperties.setProperty("loginname", loginname);
             userProperties.setProperty("password", password);
				try {
					String runningURL = (new URL(SaveUserListener.class
							.getProtectionDomain().getCodeSource().getLocation(),
							".")).openConnection().getPermission().getName();
					userProperties.save(new   FileOutputStream(new File(runningURL+"userProperties.properties")),"changed");
					
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
				
					e1.printStackTrace();
				}     
   			  
             }
           }
           
    }
    
    
    class ReLoginListener extends WebBrowserAdapter{
          	  public void locationChanged(WebBrowserNavigationEvent e) {
  		   	    if (e.getNewResourceLocation().equals("http://t.sina.com.cn")){
  		   	  	      userProperties.setProperty("loginname", "");
  	                   userProperties.setProperty("password", "");
  	             	try {
  						String runningURL = (new URL(SaveUserListener.class
  								.getProtectionDomain().getCodeSource().getLocation(),
  								".")).openConnection().getPermission().getName();
  						userProperties.save(new   FileOutputStream(new File(runningURL+"jdsclient_init.properties")),"changed");
  						
  					} catch (FileNotFoundException e1) {
  						e1.printStackTrace();
  					} catch (IOException e1) {
  					
  						e1.printStackTrace();
  					}     
  	   			  
  	             
  	                   
  				      String script="function saveuser(){" +LS+
  		         "sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+
  		         "void(0);" +LS+
  		         "}" +LS+
  		         "document.getElementById('login_submit_btn').href=\"javascript:'saveuser()'\";document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+
  		         "alert('用户名密码错误请重新输入');" +LS+
  		         "";
  					       e.getWebBrowser().executeJavascript(script);
  		           	    }
  		         
               }
   
     }
   
    
    class SsoListener extends WebBrowserAdapter{
    	  public void locationChanged(WebBrowserNavigationEvent e) {
    		  if (e.getNewResourceLocation().equals("http://t.sina.com.cn/")){
    			String loginname= userProperties.getProperty("loginname")  ;
   	            String password= userProperties.getProperty("password")  ;
   	            if ((loginname!=null &&!loginname.equals(""))  && (password!=null && !loginname.equals(""))){
	   	             String script="document.getElementById('loginname').value='"+loginname+"';" +LS+
	          		"document.getElementById('password').value='"+password+"';" +LS+
	          		"document.getElementById('login_submit_btn').click();";
	                 e.getWebBrowser().executeJavascript(script);
   	            }else{
   	             String script="function saveuser(){" +LS+
   	             "sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+
   	         
   	             "}" +LS+
   	             "document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+
   	             "alert('存储的用户名密码为空,请输入用户名密码')" +LS+
   	             "";
   	            	e.getWebBrowser().executeJavascript(script);
   	            	e.getWebBrowser().removeWebBrowserListener(this);
   	            	e.getWebBrowser().addWebBrowserListener(new ReLoginListener());

   	            }
    	        
    		  }else{
    			  System.out.println(e.getNewResourceLocation());
    		  }
    	  }       	 
     }
    

    

    webBrowser.addWebBrowserListener(new SaveUserListener());
    webBrowser.addWebBrowserListener(new SsoListener());
    
    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
  
    add(webBrowserPanel, BorderLayout.CENTER);

  }
  

  public  InputStream loadResource(String name) {
      InputStream in = this.getClass().getResourceAsStream(name);
      if (in == null) {
          in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
          if (in == null) {
              in = this.getClass().getClassLoader().getResourceAsStream(name);
          }
      }
      return in;
  }
  
  public static void main(String[] args) {
    UIUtils.setPreferredLookAndFeel();
    NativeInterface.open();
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("测试新浪微博登录");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new SSOSina(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
      }
    });
    NativeInterface.runEventPump();
    
  }
 

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值