Java传入用户名和密码并自动提交表单实现登录到其他系统的实例代码
不用单点登录,模拟远程项目的登录页面表单,在访问这个页面的时候自动提交表单到此项目的登录action,就可以实现登录到其他系统。
ssh框架项目
1.以下是本地系统的action代码:
importjava.io.IOException; importjava.util.List; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStreamReader; importjava.io.PrintWriter; importjava.net.URL; importjava.net.URLConnection; publicclassmyLoginAction{ /** *查询是否用户已注册 *@return *@throwsException */ publicvoidcheckUser()throwsException{ Loginerloginer=(Loginer)request.getSession() .getAttribute("loginer"); Stringurl="http://www.youtest.com/login.php";//远程系统登录action地址 Stringparam="username=Tom&password=123456";//参数 Stringtemp="alert('用户名或密码错误');";//返回的信息,此处是错误信息,用于比较。视情况而定 booleanresult=false; //验证数据是否能登录 result=sendPost(url,param,temp); if(result){ return"login"; }else{ return"register"; } } //访问远程登录action并获取返回的信息 publicstaticbooleansendPost(Stringurl,Stringparam,Stringtemp){ PrintWriterout=null; BufferedReaderin=null; booleanresult=true; try{ URLrealUrl=newURL(url); //打开和URL之间的连接 URLConnectionconn=realUrl.openConnection(); //设置通用的请求属性 conn.setRequestProperty("accept","*/*"); conn.setRequestProperty("connection","Keep-Alive"); conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)"); //发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); //获取URLConnection对象对应的输出流 out=newPrintWriter(conn.getOutputStream()); //发送请求参数 out.print(param); //flush输出流的缓冲 out.flush(); //定义BufferedReader输入流来读取URL的响应 in=newBufferedReader(newInputStreamReader(conn.getInputStream(),"UTF-8")); Stringline; while((line=in.readLine())!=null){ if(temp.equals((line.trim()))){ System.out.println("错误的line:"+line); result=false; } } }catch(Exceptione){ result=false; logger.error("发送POST请求出现异常!"+e); System.out.println("发送POST请求出现异常!"+e); e.printStackTrace(); }finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } }catch(IOExceptionex){ logger.error(ex); ex.printStackTrace(); } } returnresult; } }
2.模拟的登录页面:
<html> <head></head> <body> <scripttype="text/javascript"> variframe=document.createElement("iframe"); iframe.src="http://www.youtest.com/login.php?UNAME=<%=userName%>&UPWD=<%=pwd%>"; iframe.style.display="none"; varsta="false;" if(iframe.attachEvent){ iframe.attachEvent("onload",function(){ window.location.href="http://www.youtest.com/index.html"; }); }else{ iframe.onload=function(){ window.location.href="http://www.youtest.com/index.html"; }; } document.body.appendChild(iframe); </script> </body> </html>
以上所述是小编给大家介绍的Java传入用户名和密码并自动提交表单实现登录到其他系统,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!