In NetBeans IDE, select File->Open Project.
In the Open Project dialog, navigate to:
tut-install/examples/web/ |
Select the hello2 folder.
Select the Open as Main Project check box.
Expand the Source Packages node, then the servlets node.
Double-click the GreetingServlet.java file to view it.
This servlet overrides the doGet method, implementing the GET method of HTTP. The servlet displays a simple HTML greeting form whose Submit button, like that of hello1, specifies a response page for its action. The following excerpt begins with the @WebServlet annotation that specifies the URL pattern, relative to the context root:
@WebServlet("/greeting") public class GreetingServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the data of the response out.println("<html>" + "<head><title>Servlet Hello</title></head>"); // then write the data of the response out.println("<body bgcolor=\"#ffffff\">" + "<img src=\"duke.waving.gif\" alt=\"Duke waving\">" + "<h2>Hello, my name is Duke. What's yours?</h2>" + "<form method=\"get\">" + "<input 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"); if (dispatcher != null) { dispatcher.include(request, response); } } out.println("</body></html>"); out.close(); } ...
Double-click the ResponseServlet.java file to view it.
This servlet also overrides the doGet method, displaying only the response. The following excerpt begins with the @WebServlet annotation, which specifies the URL pattern, relative to the context root:
@WebServlet("/response") public class ResponseServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // then write the data of the response String username = request.getParameter("username"); if (username != null && username.length() > 0) { out.println("<h2>Hello, " + username + "!</h2>"); } } ...
Under the Web Pages node, expand the WEB-INF node and double-click the sun-web.xml file to view it.
In the General tab, observe that the Context Root field is set to /hello2.
For this simple servlet application, a web.xml file is not required.