Servlet development process:
The earliest server handlers were CGI, which created a new CGI object every time a request was processed, so it was not very satisfying in terms of speed and memory. With the rise of the JAVA language and its cross-platform nature, servlets became popular and reusable, so servlets gradually replaced CGI.
How does the Servlet handle HTTP requests for D?
- The client initiates an HTTP request to the server.
- The HTTP server receives the HTTP request and forwards it to the Web container for processing;
- The Web container parses the content of the HTTP request and stores the information in an HttpServletRequest, generating objects such as HttpResponse(for storing the information to be returned to the client), HttpSession(for managing sessions), and so on.
- Based on the REQUESTED URL, the Web container determines which specific Servlet program to forward for processing;
- Firstly, the HttpServlet service method analyzes the HTTP request is Get,Post,Put,Delete and other methods, and then decides to call the selected Servlet corresponding to each request object processing method;
- When the Servlet completes processing, the information to be returned is stored in the HttpServletResponse object species and returned to the Web container for parsing and conversion into an HTTP response that is returned to the client.
How does the Web container find the Servlet handler corresponding to a specific URL?
Let’s first look at the Servlet creation process:
- In Servlet3.0 and beyond, it is supported to provide the Web container with information about this Servlet via @webServvelt annotations, such as urlPatterns, name (if not defined, The default is the class name of the Servlet), loadOnStartup(used to indicate that the Servlet is preloaded, rather than waiting until it is needed), and so on; The same applies to web. XML.
- The user-written Servlet inherits from HttpServlet and then overrides HttpServlet’s doGet(), doPost() and other methods that the Servlet overrides to complete the creation;
- The Web container can then read the information provided by these annotations to find the Servlet corresponding to the specific URL and load it for processing.
How do YOU filter HTTP methods through the HttpServlet service method?
User-written servlets inherit from HttpServlet, as shown below:
- First, the final string constant defines eight HTTP methods and identifies whether they have been modified.
- It then provides default implementations of handlers for eight HTTP methods that would be overridden if used;
- So if you look at the service method, you can see that the input parameter is a ServletRequest, a ServletResponse, and there is no Http identifier, because servlets were originally designed to handle more than JUST Http requests, So the basic behavior specification for the request/corresponding object is in ServletRequest(the package is Javax.servlet), and the http-related behavior is defined by its sub-interface HttpServletRequest(the package is Javax.servlet, HTTPD). This object is therefore strongly typed in HttpServlet;
- In the service method by calling it. GetMethod () method is used to get the HTTP method, and corresponding treatment methods of jump by an if statement.
How do you pass the processed information back to the client via an HttpServletResponse object?
Servlets are reusable:
After looking at how the Web container handles HTTP messages, we mentioned earlier that servlets are reusable, does that mean they are shared by threads, and does that make them thread unsafe?
To clarify this problem, let’s first look at how the Web container loads servlets:
- The first thing to know is that the Web container is a Java program that runs on top of the JVM and is a process of the JVM. Why not access the Tomcat container via localhost:8080?
- However, unlike traditional Java containers, Web containers not only hold objects, but are also responsible for their lifetime of connection to related services.
- The Web container loads the corresponding Servlet instance (if not already loaded) for each request and allocates a thread, so there may be problems with multiple threads sharing a Servlet instance, which can be solved with ThreadLocal or by separating processing of URL requests from processing of data business logic. That is to use MVC framework, and then use lock and other mechanisms in the data business logic to ensure data security.
Implementing the MVC framework with servlets:
- First implement the Model(that is, a normal POJO), then provide get, set mechanisms;
- Controller: a Servlet
@WebServlet("/HelloController")
public class HelloController extends HttpServlet {
private static final long serialVersionUID = 1L;
private HelloModel model = new HelloModel();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Cookie[] cookies = request.getCookies();
if(cookies ! = null) {for(Cookie cookie : cookies) {
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
request.setAttribute("name", cookieName);
request.setAttribute("value", cookieValue); }}else {
Cookie cookie = new Cookie("user"."cjc");
cookie.setMaxAge(7 * 24 * 60 *60);
response.addCookie(cookie);
}
String name = request.getParameter("user");
String message = model.doHello(name);
request.setAttribute("message", message);
request.getRequestDispatcher("HelloServlet").forward(request, response); }}Copy the code
As with SpringMVC, the Controller returns the Model to the View for rendering. In this case, the model data is put into the properties of the HttpServletRequest object. We then forward the request (forward) through the RequestDispatcher object to our HelloServlet, which is our View, for processing; 3. View: a Servlet that completes the HttpServletResponse object and returns it to the client;
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String user = request.getParameter("user");
String message = (String) request.getAttribute("message");
String cookieName = (String)request.getAttribute("name");
String cookieValue = (String)request.getAttribute("value");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Hello!" + user + ! "" ");
out.println(message);
out.println("<h1> cookieName" + cookieName + cookieValue + ! "" ");
out.println("</body>");
out.println("</html>"); out.close(); }}Copy the code
So far, we have implemented an MVC framework through servlets, separating the LOGIC of dealing with URLS, business logic and page rendering logic, which were originally done through a Servlet, which makes the system uncoupled, the architecture clearer and easier to maintain.