Java Servlet and JSP tutorial (3)
3 Servlet
3.1 basic Servlet Structure
The following code shows the basic structure of a simple Servlet. The Servlet processes GET requests. If you are not familiar with HTTP, it can be viewed as a request sent by the browser when a user enters a URL in the browser address bar, clicks a link on the Web page, and submits a form without a specified METHOD. Servlet can also easily process POST requests. A POST request is a request sent when a form with the specified METHOD = "POST" is submitted. For more information, see the following sections.
Import java. io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Public class SomeServlet extends HttpServlet {
Public void doGet (HttpServletRequest request,
HttpServletResponse response)
Throws ServletException, IOException {
// Use "request" To Read request-related information (such as Cookies)
// And form data
// Use "response" to specify the HTTP response status code and response Header
// (For example, specify the content type and set the Cookie)
PrintWriter out = response. getWriter ();
// Use "out" to send the response content to the browser
}
}
If a class is to be a Servlet, it should inherit from HttpServlet, and be sent through GET or POST based on the data, overwriting one or all of the doGet and doPost methods. The doGet and doPost methods both have two parameters: HttpServletRequest and HttpServletResponse. HttpServletRequest provides methods to access request information, such as form data and HTTP request headers. HttpServletResponse provides methods to specify the HTTP response status (200,404, etc.), Response Header (Content-Type, Set-Cookie, etc, most importantly, it provides a PrintWriter for sending data to the client. For a simple Servlet, most of its work is to generate a page sent to the client through the println statement.
Note that doGet and doPost throw two exceptions, so you must include them in the Declaration. In addition, you must import java. io packages (PrintWriter and other classes are used), javax. servlet package (use HttpServlet and other classes) and javax. servlet. http packet (the HttpServletRequest class and HttpServletResponse class are required ).
Finally, the doGet and doPost methods are called by the service method. Sometimes you may need to directly overwrite the service method. For example, when the Servlet needs to process GET and POST requests.
3.2 simple Servlet for outputting plain text
Below is a simple Servlet that outputs plain text.
3.2.1 HelloWorld. java
Package hall;
Import java. io .*;