Servlet
-
What is a Servlet
- Servlet is one of the Java EE specifications. A specification is an interface
- Servlet is one of the three major components of Java Web. The three components are servlet program, Filter filter and Listener listener
- Servlet is a Java applet running on the server. It can accept requests sent by the client and respond to data to the client
-
How to implement Servlet
-
Write a class to implement the Servlet interface
-
Implement the service method, process the request and respond to the data
-
On the web In the XML file, configure the access address
Step 1 and step 2
public class HelloServlet implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } /** * service Dedicated to handling responses and requests * @param servletRequest * @param servletResponse * @throws ServletException * @throws IOException */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("helloservlet Called"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
Configure web XML file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- servlet Label to Tomcat to configure servelet program --> <servlet> <!-- servlet-name to servlet The program has an alias(Usually the class name) --> <servlet-name>HelloServlet</servlet-name> <!-- servlet-class yes servlet The full class name of the program --> <servlet-class>com.yellowstar.servlet.HelloServlet</servlet-class> </servlet> <!-- servlet-mapping Label to serlvet Program configuration access address --> <servlet-mapping> <!-- there servlet-name Pointing up servlet-nameļ¼Tell the server which path this path is configured with servlet programmatic --> <servlet-name>HelloServlet</servlet-name> <!-- url-pattern The tag is used to configure the access address --> <!-- /hello refer to http://ip: port number / Project path / hello -- > <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
-
-
Servlet lifecycle
The first and second steps are called when the servlet is an object during the first access; Step 3: call the service method every time it is executed; The fourth step is executed when the program is closed
- Construction method
- Execute init initialization method
- Execute the service method
- Execute destroy destroy method
-
Distribution and processing of Servlet requests -- GET and POST
Generally speaking, there are two kinds of requests from the client to the server: GET or POST. For two different requests, we need to process them in the service
Let's create a page to simulate this requirement
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://localhost:8080/Demo01/hello" method="post"> <input type="submit"> </form> </body> </html>
Next, we implement the service processing of the class in the servlet
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { //Create a subclass of servletRequest httpServletRequest HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; //Call HttpServletRequest Getmethod () to get the passed method name String method = httpServletRequest.getMethod(); if("GET".equals(method)){ doGet(); }else if("POST".equals(method)){ doPost(); } } //get request processing method public void doGet(){ System.out.println("get request"); } //post request processing method public void doPost(){ System.out.println("post request"); }
-
Inherit HttpServlet to create servlet program
Java provides the HttpServlet class. We only need to inherit this class and rewrite doGet() and doPost() to realize the above cumbersome operations
public class HelloServlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("this is doget"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("this is dopost"); } }
-
Next, let's look at how HttpServlet is implemented
Servlet interface: it is only responsible for defining the access specification of servlet program
public interface Servlet { void init(ServletConfig var1) throws ServletException; ServletConfig getServletConfig(); void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException; String getServletInfo(); void destroy(); }
GenericServlet class: it implements the servlet interface and makes many empty implementations
At the same time, a ServletConfig object is created in this class, and some methods are made for the use of this object
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable { private static final long serialVersionUID = 1L; private transient ServletConfig config; ...... }
HttpServlet abstract class: inherits the GenericServlet class, implements the service() method, and distributes the request
As we can see below, the implemented method is similar to our handwritten method. It is also a method to obtain the request, judge the specific method and do distribution processing
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); long lastModified; if (method.equals("GET")) { lastModified = this.getLastModified(req); if (lastModified == -1L) { this.doGet(req, resp); } else { long ifModifiedSince; try { ifModifiedSince = req.getDateHeader("If-Modified-Since"); } catch (IllegalArgumentException var9) { ifModifiedSince = -1L; } if (ifModifiedSince < lastModified / 1000L * 1000L) { this.maybeSetLastModified(resp, lastModified); this.doGet(req, resp); } else { resp.setStatus(304); } } } else if (method.equals("HEAD")) { lastModified = this.getLastModified(req); this.maybeSetLastModified(resp, lastModified); this.doHead(req, resp); } else if (method.equals("POST")) { this.doPost(req, resp); } else if (method.equals("PUT")) { this.doPut(req, resp); } else if (method.equals("DELETE")) { this.doDelete(req, resp); } else if (method.equals("OPTIONS")) { this.doOptions(req, resp); } else if (method.equals("TRACE")) { this.doTrace(req, resp); } else { String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[]{method}; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(501, errMsg); } }
Take doGet() as an example. We can see that the methods in this abstract class are responsible for throwing exceptions (Get/Post requests are not supported)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String msg = lStrings.getString("http.method_get_not_supported"); this.sendMethodNotAllowed(req, resp, msg); }
Finally, we customize the Servlet program: we only need to inherit HttpServlet and rewrite its methods according to business needs