Creating an HTTP servlet usually involves the following four steps:
1. Extend the HTTP servlet abstract class.
2. Reload the appropriate method.] For example, override (or rewrite) The doget () or dopost () method.
3. Obtain the HTTP request information. Use the httpservletrequest object to retrieve the HTML table
The submitted data or query string on the URL. The "request" object contains specific methods to retrieve information provided by the client. There are three available methods:
Getparameternames (),
Getparameter (),
Getparametervalues ().
4. generate an HTTP response. The httpservletresponse object generates a response and returns it to the client sending the request. It
You can set the request title and response body. The response object also contains the getwriter () method to return a printwriter object. Use the print () and println () Methods of printwriter to write the servlet response and return it to the client. Alternatively, you can directly use the out object to output HTML document content.
A servlet sample (servletsample. Java) is as follows:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
Public class servletsample extends httpservlet {// Step 1: Expand the httpservlet abstract class. public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws servletexception, ioexception {// Step 2: override the doget () methodString myname = ""; // Step 3: get http Request Information
java.util.Enumeration keys = request.getParameterNames();
while (keys.hasMoreElements());
{key = (String) keys.nextElement();
if (key.equalsIgnoreCase("myName"))myName = request.getParameter(key);
}
if (myName == "")
myName = "Hello";
// Step 4: generate an HTTP response.
response.setContentType("text/html");response.setHeader("Pragma", "No-cache");response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-cache"); PrintWriter out=response.getWriter();
out.println("out.println("<body>");out.println("out.println ("<p>" + myName + ",how are you.");out.println("</body>out.flush();
}
}
The above servletsample class extends the httpservlet abstract class and overrides the doget () method. In the rewritten doget () method, obtain an optional parameter (myname) in the HTTP request. This parameter can be passed to the Servlet as a query parameter on the called URL.