JAVA中虚拟的POST提交
在java中我们难免会遇到需要从后台进行携带参数虚拟的POST提交,用于过滤器的拦截或者其他用处,查阅了些资料也试了很多方法,最后选择一种本人觉得非常好用的虚拟表单POST提交的方式进行提交接下来请看代码.
我们需要新建一个文件,方便调用,代码如下
public class DoPost {
//参数的容器
Map<String, String> parameter = new HashMap<String, String>();
HttpServletResponse response;
//POST请求的方法
public DoPost(HttpServletResponse response) {
this.response = response;
}
//参数的封装
public void setParameter(String key, String value) {
this.parameter.put(key, value);
}
//虚拟POST提交
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();
}
}
到这我们就可以调用了
//在java的controller中的操作
DoPost dopost = new DoPost(response);
//参数的封装
dopost.setParameter("username","账户名");
dopost.setParameter("password","登录密码"));
//传入想要跳转的路径地址
dopost.sendByPost(url);
return null;
感谢大家,欢迎朋友们提出意见与建议.有什么不合适的可以在评论区交流