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.
- 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)
-
- PrintWriterOut=Response. GetWriter ();
- // Use "out" to send the response content to the browser
- }
- }
The basic structure of the Servlet. If a class is to be a Servlet, it should inherit from the 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 for specifying HTTP response status 200,404, etc.), response header Content-Type, Set-Cookie, and so on, 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. i/O packages use PrintWriter and other classes), javax. the servlet package must use HttpServlet and other classes) and javax. servlet. the HttpServletRequest class and HttpServletResponse class are used for the http package ).
Finally, the doGet and doPost methods are called by the service method. Sometimes you may need to directly overwrite the service method. The above is the basic Servlet Structure
- Introduction to functions of Servlet 2.4
- Introduction to multiple Servlet Interfaces
- Interface introduction-Servlet Context
- Servlet Registration Method
- Introduction to Servlet containers