GreetingServlet.java:
@WebServlet("/greeting")//指定URL模式,在根目录下使用/greeting访问
public class GreetingServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,//重写doGet方法
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setBufferSize(8192);
try (PrintWriter out = response.getWriter()) {//实例化对象out
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");//将得到的值赋值给一个字符串username
if (username != null && username.length() > 0) {//判断值是否不为空并且长度大于0
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/response");//把命令发送到浏览器,浏览器对指定的URL提出请求
if (dispatcher != null) {
dispatcher.include(request, response);//整合request,response跳转
}
}
out.println("</body></html>");
}
}
@Override
public String getServletInfo() {
return "The Hello servlet says hello.";
}
}
ResponseServlet.java:
@WebServlet("/response")//指定URL的模式,在根目录下使用/response访问
public class ResponseServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,//重写doGet方法
HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {//实例化对象out
String username = request.getParameter("username");//将输入的值赋值给username
if (username != null && username.length() > 0) {
out.println("<h2>Hello, " + username + "!</h2>");
}
}
}
@Override
public String getServletInfo() {
return "The Response servlet says hello.";
}
}