Java(servlet)模拟表单提交

本文介绍了如何使用Java Servlet模拟表单POST提交的过程,包括设置请求方法、发送参数、接收响应等内容。示例代码展示了如何创建HttpURLConnection并写入参数,以及服务端如何接收并处理这些参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java(servlet)模拟表单提交

String userName = request.getParameter(“userName”);
String redirectURL=”“;
response.setContentType(“text/html”);
PrintWriter redirectOut=null;
try {
redirectOut = response.getWriter();
URL url=new URL(“http://localhost:8081/LDAPPro/LoginServlet“);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod(“POST”);
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), “UTF-8”);
// 向服务端发送key = value对
out.write(“username=”+userName);
out.flush();
out.close();
// 获取服务端的反馈
InputStream in =conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int c;
while ((c=reader.read())!=-1) {
out.write(c);
}
} catch (MalformedURLException e) {
e.printStackTrace();
redirectOut.write(“404”);
} catch (IOException e) {
e.printStackTrace();
redirectOut.write(“404”);
}
服务端的servlet可以这么写:
public classHandlingHttpRequestServlet extends HttpServlet
{
private static final longserialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequestreq, HttpServletResponse resp)
throws ServletException, IOException
{super.doGet(req, resp);}
@Override
protected voiddoPost(HttpServletRequest req, HttpServletResponse resp)
throwsServletException, IOException
{
String username =req.getParameter(“username”); //获取username所对应的value
String password =req.getParameter(“password”); //获取password所对应的value
System.out.println(“Thereceived username and password is: ” + username + “/” +password);
// 向请求端发回反馈信息
PrintWriter out =resp.getWriter();
out.print(“OK”);
out.flush();
out.close();
// super.doPost(req, resp);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值