编写一个servlet程序,在doget方法中显示一个form表单,用户可以输入姓名和电子邮件地址,用户提交该表单后,dopost方法动态读出请求参数,并输出这些参数。
时间: 2023-07-16 07:15:06 浏览: 125
request请求获取参数的实现方法(post和get两种方式)
好的,这是一个Java Servlet的基础问题,我可以为您提供样例代码,参考如下:
```
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>My Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<form method=\"post\">");
out.println("Name: <input type=\"text\" name=\"name\"><br>");
out.println("Email: <input type=\"text\" name=\"email\"><br>");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
out.println("<html>");
out.println("<head>");
out.println("<title>My Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + name + "!</h1>");
out.println("<p>Your email address is: " + email + "</p>");
out.println("</body>");
out.println("</html>");
}
}
```
您可以将以上代码保存为MyServlet.java文件,并将其部署到Web服务器上(例如Tomcat),然后访问http://localhost:8080/MyServlet即可看到表单界面。当您填写表单并提交后,服务器会读取您输入的姓名和电子邮件地址,并显示在页面上。注意,在实际部署时,您需要将上述代码中的“http://localhost:8080/MyServlet”替换为您的Servlet的URL路径。
阅读全文