接受参数和表单提交,使项目变得更加有交互性
程序员文章站
2022-05-29 23:11:41
...
接受参数和表单提交,使项目变得更加有交互性
package day0301;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(
name = "helloServlet",
urlPatterns = {"/greeting", "/salutation", "/wazzup"},
loadOnStartup = 1
)
public class HelloServlet extends HttpServlet
{
private static final String DEFAULT_USER = "Guest";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// response.getWriter().write("This is My User Servlet");
String user = request.getParameter("user");
if (user == null) {
user = HelloServlet.DEFAULT_USER;
}
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.append("<!DOCTYPE html>\r\n")
.append("<html>\r\n")
.append(" <head>\r\n")
.append(" <title>Hello User Application</title>\r\n")
.append(" </head>\r\n")
.append(" <body>\r\n")
.append(" Hello, ").append(user).append("!<br/><br/>\r\n")
.append(" <form action=\"greeting\" method=\"POST\">\r\n")
.append(" Enter your name:<br/>\r\n")
.append(" <input type=\"text\" name=\"user\"/><br/>\r\n")
.append(" <input type=\"submit\" value=\"Submit\"/>\r\n")
.append(" </form>\r\n")
.append(" </body>\r\n")
.append("</html>\r\n");
}
/*
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doGet(request, response);
}
@Override
public void init() throws ServletException
{
System.out.println("Servlet " + this.getServletName() + " has started.");
}
@Override
public void destroy()
{
System.out.println("Servlet " + this.getServletName() + " has stopped.");
}
}
代码实现了一点逻辑:
- 检测请求中是否包含user参数,如果未包含,就使用 DEFAULT USER常量。
- 将响应的内容类型设置为 text/html,并将字符编码设置为UTF-8
- 从响应中获得一个 Printwriter,并输出一个兼容于HIML5的文档(注意HIML5的DOCTYPE),其中包括问候(现在它将间候某个特定的用户和一个用于提供用户名的表单
当表单的方法类型设置为POST时, doget方法使用一个单的doPost实现对请求进行处理。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doGet(request, response);
}
该实现将请求委托给doGet方法,一个名为user的查询参数或者post变量都将改变页面中问候的内容。
配置Servlet之后 Hello, Guest!