GreetingServlet.java源码:
@WebServlet("/greeting") //以@WebServlet注释开头,表示在根目录下使用/greeting来访问
public class GreetingServlet extends HttpServlet
{
@Override
public void doGet(HttpServletRequest request, //重写了doGet方法,实现GET HTTP方法
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html"); //指定响应页面的类型为html
response.setBufferSize(8192); //指定缓冲区大小8192
try (PrintWriter out = response.getWriter()) { //实例化对象out,作为向html页面输出的对象
//使用println属性,向html页面输出html标签,这里输出的是:
out.println("<html lang=\"en\">"
+ "<head><title>Servlet Hello</title></head>");
//使用println属性,向html页面输出html标签
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>");
//使用println属性,向html页面输出html标签
String username = request.getParameter("username"); //使用一个字符串username来获取,第一个input标签内的username的值
if (username != null && username.length() > 0) {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/response");
//指定要跳转的页面相对于上下文根的URL模式为/response
if (dispatcher != null) {
dispatcher.include(request, response);//整合request, response然后跳转
}
}
out.println("</body></html>");//使用println属性,向html页面输出html标签
}
}
ResponseServlet.java源码:
@WebServlet("/response") //以@WebServlet注释开头,表示在根目录下使用/response来访问。
public class ResponseServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, //重写了doGet方法,实现GET HTTP方法
HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) { //实例化对象out,作为向html页面输出的对象
String username = request.getParameter("username"); //接收来自greting页面请求中的input标签中输入的username if (username != null && username.length() > 0){
out.println("<h2>Hello, " + username + "!</h2>");//使用println属性,向html页面输出html标签
}
}
}
原文:https://www.cnblogs.com/railgun1/p/10836089.html