The basic concept

  • Server applets (Servlets) are short for Java servlets. Servlets are server-side programs written in The Java language. That is, servlets are Java classes running on servers
  • Servlet is used to complete the response processing of client requests under THE B/S architecture, that is, to interactively browse and generate data and generate dynamic Web content

Write the steps

  • Set up a Java Web Application project and configure the Tomcat server
  • Custom classes implement the Servlet interface or inherit the HttpServlet class (recommended) and override the Service method
  • Configure the information for the custom class into the web.xml file and start the project
<! --web.xml-->
<! Servlet configuration -->
<servlet>
    <!--对 Servlet 起别名-->
    <servlet-name>hello</servlet-name>
    <! Specify the corresponding Servlet class -->
    <servlet-class>com.yamin.servlet.HelloServlet</servlet-class>
</servlet>
<! Servlet mapping -->
<servlet-mapping>
    <! Select Servlet to map, must be the same as the alias of the Servlet.
    <servlet-name>hello</servlet-name>
    <! -- Configure access address -->
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
Copy the code

Servlet

The Servlet interface

The javax.servlet. servlet interface is used to define the methods that all servlets must implement

methods function
void init(ServletConfig config) There are servlet container calls to indicate to the servlet that the servlet is being put into the service
void service(ServletRequest req,ServletResponse res) There are servlet container calls to allow the servlet to respond to requests
ServletConfig getServletConfig() Returns a ServletConfig object that contains the initialization and startup parameters for this servlet
String getServletInfo() Returns information about the Servlet, such as author, copyright, and version
void destory() There are servlet container calls to indicate to the servlet that the servlet is exiting the service

GenericServlet class

Javax.mail. Servlet. GenericServlet class is mainly used to define a generic and has nothing to do with the agreement of the servlet, the class implements the servlet interface, if write general servlet, you just need to rewrite the service abstraction method

methods function
abstract void service(ServletRequest req,ServletResponse res) There are servlet container calls to allow the servlet to respond to requests

The HttpServlet class

Javax.mail. Servlet. The HttpServlet class is an abstract class and inherit the GenericServlet class, used to create the use and site of the HTTP servlet, a subclass of the class have to rewrite at least one way

methods function
void doGet(HttpServletRequest req,HttpServletResponse res) Process client GET requests
void doPost(HttpServletRequest req,HttpServletResponse res) Process client POST requests
void init() Initialization is performed
void service(HttpServletRequest req,HttpServletResponse res) Call the doGet or doPost method depending on the request
void destory() Resources are released when instances are deleted

ServletRequest interface

Javax.mail. Servlet. ServletRequest interface is mainly used to provide the client request information to the servlet, you can get to any request information, the servlet container creates a ServletRequest object, And pass it as a parameter to the Servlet’s Service method

methods function
String getParameter(String name) Returns the value of the request parameter as a string, or null if it does not exist
String[] getParameterValues(String name) Returns an array of string objects containing all the values locked for the given request parameter, or null if the parameter does not exist
Enumeration getParameterNames() Returns an enumeration of the string object containing the names of the parameters contained in this request, or the method returns an empty enumeration if the request has no parameters
Map<String,String[]> getParameterMap() Returns a key-value pair of the request parameter. One key can correspond to multiple values
String getRemoteAddr() Returns the IP address of the client or last proxy that sent the request
int getRemotePort() Returns the port number of the client or last proxy that sent the request

It interfaces

This interface is a subinterface of the ServletRequest and is used to provide HTTP request information. Unlike form data, HTTP request headers are set directly by the browser when sending HTTP requests.

methods function
String getRequestURI() Returns the resource path information for this request
StringBuffer getRequestURL() Returns the full path information for this request
String getMethod() Returns the type of HTTP method that made the request, such as GET POST
String getQueryString() Returns the parameters attached to the request following the path
String getServletPath() Returns the path portion of this request calling the servlet

ServletResponse interface

Use to define an object to help the Servlet send a response to the client

methods function
PrintWriter getWriter() Returns a PrintWriter object that sends character text to clients
String getCharacterEncoding() Gets the encoding of the response content
void setContentType(String type) If the response has not been submitted, set the content type of the response sent to the client,

Content types can include character encoding specifications, such as text/ HTML; charset=utf-8

HttpServletResponse interface

The ServletResponse interface is inherited from the ServletResponse interface to provide HTTP-specific functionality in a send response

methods function
void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL

ServletConfig interface

Configuration information that describes the Servlet itself and is used to pass information to the Servlet configuration object during initialization

methods function
String getServletName() Returns the alias of the Servlet
String getInitParameter(String name) Returns a string containing the value of the initialization parameter, or null if the parameter does not exist
Enumeration getInitParameterNames() Returns the servlet’s initialization parameter name as an enumeration of string objects,

If the servlet has no initialization parameters, an empty enumeration is returned
ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing

The ServletContext interface

  • Primarily used to define a set of methods that a Servlet uses to communicate with its Servlet container
  • The server will have a unique ServletContext object for each project when it starts, which is used to realize information sharing and communication between servlets
  • This can be used in servletsthis.getServletContext()Get the ServletContext object.
  • Configuration mode
<! Set the initialization parameters of the servletContext in web.xml.
<context-param>
    <param-name>key1</param-name>
    <param-value>value1</param-value>
</context-param>
<context-param>
    <param-name>key2</param-name>
    <param-value>value2</param-value>
</context-param>
Copy the code
methods function
String getInitParameter(String name) Returns a string containing the value of the initialization parameter, or null if the parameter does not exist
Enumeration getInitParameterNames() Returns the servlet’s initialization parameter name as an enumeration of the string object, or an empty enumeration if the servlet has no initialization parameters
String getRealPath(String path) Returns a string containing the actual path for the given virtual path
String getContextPath() Returns the main path associated with this context
InputStream getResourceAsStream(String path) Returns the resource at the specified path as an InputStream object
void setAttrbute(String name,Object value) Binds the specified property name and value to the current object (able to communicate across servlets)
Object getAttrbute(String name) Get property values based on executing property names (able to communicate across servlets)
void removeAttrbute(String name) Delete the specified attribute name information (able to communicate across servlets)

The life cycle of a Servlet

Instantiate (the container creates an instance of the Servlet, which calls the constructor of the Servlet) ↓ Initialize (the Servlet calls the init() method) ↓ Service (a request comes into the Servlet, This Servlet called the service() method.) ↓ Destroyed (this Servlet called the destory() method.) ↓ Unavailable (Destroy the Servlet and mark it as garbage collection)Copy the code
  • The constructor is called only once, the first time the Servlet is requested it is called to create the instance
  • The init method is called only once, immediately after the instance is created
  • The Service method can be called multiple times, each time a request comes into the Servlet
  • The deStory method is called only once, before the web application in which the instance resides is uninstalled, to release the currently occupied resources

Thread safety

  • When a request is received, a thread is started to make the corresponding request.
  • By default, the server creates only one instance per Servlet, and thread-safety issues can occur when multiple requests access the same Servlet and multiple threads access the same Servlet object

State management

  • Web applications communicate over HTTP, a “stateless” protocol that disconnects once a server has responded to a client’s request, and allows the same client to re-establish a network connection with its next request
  • Sometimes the server program needs to determine whether a request is made for the same customer, such as multiple purchases by the customer, so it is necessary to track a series of requests from the same customer
  • The multiple monitoring between browser and server is taken as a whole, and the data involved in multiple interlocking is saved, that is, state management
  • Data states of multiple interactions can be saved on the client side or the server side. State management is mainly divided into the following two types:
    • Client management: the state is saved in the client, based on Cookie technology
    • Server management: Saves state on the server, based on the Session technology

Cookie technology

The basic concept

  • Cookie here refers to a technique by which a client saves data in key-value form
  • When the browser sends a request, the server responds with the data in the form of a set-cookie header to the browser, which then saves the data as a text file
  • When the browser visits the server again, it sends this data to the server in the form of a Cookie header

Relevant methods

  • . Use javax.mail. Servlet. HTTP cookies class constructor to realize the creation of a Cookie
methods function
Cookie(String name,String value) Constructs an object by specifying a value as an argument
  • Using the javax.mail. Servlet. HTTP. Members of the HttpServletResponse interface can realize the add of cookies
methods function
void addCookie(Cookie cookie) Adds the specified Cookie to the response
  • Use javax.mail. Servlet. HTTP. It the members of the interface methods to realize the Cookie object access
methods function
Cookie[] getCookie() Returns all Cookie objects contained in this request
  • . Use the javax.mail. Servlet. HTTP cookies class members of the method to realize the Cookie object attribute access and modification
methods function
String getName() Returns the name of this Cookie object
String getValue() Returns the value of this Cookie object
void setValue(String newValue) Sets the value of this Cookie object

Cookie life cycle

  • By default, the browser keeps Cookie information in memory and the Cookie disappears when the browser is closed
  • If you want the Cookie information to remain valid after closing the browser, you can set it through the Cookie class member method
methods function
int getMaxAge() Maximum lifetime to get cookies in seconds
void setMaxAge(int expiry) Set the maximum lifetime of cookies (seconds)

Routing problem

  • When accessing the server, the browser compares whether the Cookie path matches the request path and sends only matched cookies to the server
  • The default path of the Cookie is equal to the path of the component to which the Cookie information was added, for example: / project name/directory/Cookie Request added a Cookie information, the path of the Cookie is: / project name/directory
  • The browser will send Cookie information only when the requested address matches the Cookie path or its subpath
  • Path information can be set through the member methods of cookies
methods function
void setPath(String url) Example Set the path information of the Cookie

The characteristics of

Cookie technology is not suitable for storing all data, only for storing a small amount of non-sensitive information, for the following reasons:

  • It is not safe to save status data in the browser
  • The amount of data saved is limited to about 4KB
  • Only string information can be saved
  • Cookies can be disabled through browser Settings

The Session technology

The basic concept

  • Session means “session” and is used to maintain the technology associated with each client and server
  • When the browser accesses the server, the server allocates space in memory for each browser to create a session object. This object has a unique ID attribute called sessionId. The server sends the sessionId as a Cookie to the browser for storage
  • When the browser accesses the server again, it sends the session ID to the server, and the server searches for the corresponding session object based on the session ID

Relevant methods

  • Use javax.mail. Servlet. HTTP. It the members of the interface methods access to the session
methods function
HttpSession getSession() Returns the session associated with this request, or creates one if none exists
  • Using javax.mail. Servlet. HTTP. Members of the HttpSession interface method to judge and access
methods function
boolean isNew() Check whether it is a newly created session
String getId() Gets the session number
  • Use the javax.mail. Servlet. HTTP. Members of the HttpSession interface method realized the management of properties
methods function
Object getAttribute(String name) Gets the object with the specified name in this session, or returns null if none is present
void setAttribute(String name,Object value) Sets the value of the property named in this session
void removeAttribute(String name) Deletes the object with the specified name in this session

The life cycle

  • To save server memory resources, the server automatically clears session objects that are idle for a long time. The default timeout limit is 30 minutes
  • Can use javax.mail. Servlet. HTTP. Members of the HttpSession interface methods to set the failure time
methods function
int getMaxInactiveInterval() Get time of failure (seconds)
void setMaxInactiveInterval(int interval) Set failure time (s)
  • You can also set the expiration time (in minutes) via web.xml
<session-config>
	<session-timeout>30</session-timeout>
</session-config>
Copy the code

The characteristics of

  • Data security
  • The saved data types are rich
  • It can hold more data
  • Data stored on the server occupies the memory space of the server. If too much data is stored and too many users are used, the server performance deteriorates