public class GreetingServlet extends HttpServlet {
//使用doget方法,传入request和response两个参数,返回text/html且最大字节数为8192
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html");
response.setBufferSize(8192);//向客户端浏览器页面输入前端数据
try (PrintWriter out = response.getWriter()) { out.println("<html lang=\"en\">" + "<head><title>Servlet Hello</title></head>"); // then write the data of the response out.println("<body bgcolor=\"#ffffff\">" + "<img src=\"resources/images/duke.waving.gif\" " + "alt=\"Duke waving his hand\">" + "<form method=\"get\">" + "<h2>Hello, my name is Duke. What's yours?</h2>" + "<input title=\"My name is: \" type=\"text\" " + "name=\"username\" size=\"25\"/>" + "<p></p>" + "<input type=\"submit\" value=\"Submit\"/>" + "<input type=\"reset\" value=\"Reset\"/>" + "</form>");String username = request.getParameter("username");
if (username != null && username.length() > 0) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/response");//若username不为空,则使用dispatcher接收客户端请求并发送到服务器 if (dispatcher != null) { dispatcher.include(request, response);//若客户端请求不为空,则响应资源 } } out.println("</body></html>"); } }@Override
public String getServletInfo() { return "The Hello servlet says hello.";}
}
@WebServlet("/response")
public class ResponseServlet extends HttpServlet {@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (PrintWriter out = response.getWriter()) {//对用户输入的信息进行判别,并通过responseServlet进行处理
String username = request.getParameter("username"); if (username != null && username.length() > 0) { out.println("<h2>Hello, " + username + "!</h2>"); } } }@Override
public String getServletInfo() { return "The Response servlet says hello.";