这几天做的一个项目,需要模拟单点登录,把账号密码等信息通过组url的方式组成url重定向到后端,然后完成验证登录。
但是后来发现,如果验证失败,比如密码不正确,那么页面的地址栏就会有问题了:
1.会把参数信息暴露出来
2.再次输入密码和账户将会没有意义,因为表单依旧会提交地址栏的账号密码参数。
因为重定向的请求都是get请求,所以参数会显示在地址栏。而参数也无法通过request传递,所以只有想办法把模拟登陆的请求变成get形式。于是,找到办法写一个HttpClient类解决:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
/**
* 用于模拟表单提交方式登陆
* Created by LJM on 2018/7/5.
*/
public class HttpClient {
Map<String, String> parameter=new HashMap<String, String>();
HttpServletResponse response;
public HttpClient(HttpServletResponse response)
{
this.response=response;
}
public void setParameter(String key,String value)
{
this.parameter.put(key, value);
}
public void sendByPost(String url) throws IOException
{
this.response.setContentType("text/html");
PrintWriter out = this.response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>sender</TITLE></HEAD>");
out.println(" <BODY>");
out.println("<form name=\"submitForm\" action=\""+url+"\" method=\"post\">");
Iterator<String> it=this.parameter.keySet().iterator();
while(it.hasNext())
{
String key=it.next();
out.println("<input type=\"hidden\" name=\""+key+"\" value=\""+this.parameter.get(key)+"\"/>");
}
out.println("</from>");
out.println("<script>window.document.submitForm.submit();</script> ");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
并且在业务类里写:
HttpClient http = new HttpClient(response); http.setParameter("username", userName); http.setParameter("password", password); http.setParameter("clientIP", clientIP); http.setParameter("serviceIP", cmsBaseIP); //post方式重定向登陆 http.sendByPost(casLoginUrl.toString()); return null;通过这种形式把参数传递进去,然后通过表单提交POST请求。