Javaweb Note 2: Servlet

concept

Servlet is a Java applet running on the server side. It is a set of specifications (interfaces) provided by sun company to process client requests and respond to dynamic resources of the browser. But the essence of servlet is java code, which dynamically outputs content to the client through java API.

servlet specification: Contains three technical points, which are servlet technology; filter (filter) technology; listener (listener) technology.

Servlet implementation

Implementation steps:

  • Create a class that implements the Servlet interface
  • Override a method that has not been implemented—the service method
  • Configure the servlet in web.xml
    But in actual development, we will not directly implement the Servlet interface, because there are too many methods that need to be covered. We generally create a class that inherits HttpServlet.
    insert image description here
public MyServlet extends HttpServlet{
    
    
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        this.doGet(req,resp);
    }
}

Servlet life cycle

When were Servlets created? By default, the object is created when the servlet is accessed for the first time

When is the servlet destroyed? The server closes the servlet and destroys it

A method that must be executed every time it is accessed? service(ServletRequest req, ServletResponse res) method

Question: 10 visits to XXXServlet, how many execution times are init(), destroy(), service(), doGet(), doPost() in total? How many request objects are created? How many responses are created?

Answer: init(), 1 time; destroy(), the server is not closed, not executed; service(), 10 times; request object creation 10 times; response creation 10 times

Servlet configuration

<servlet>
  <servlet-name>ServletName</servlet-name>   
  <servlet-class>xxxpackage.xxxServlet</servlet-class>   <!--Servlet的类-->
  <init-param>                                     <!--初始化一个变量,可看成全局变量,可省略-->
    <param-name>参数名称</param-name>              <!--变量名称-->

    <param-value>参数值</param-value>              <!--变量值-->
  </init-param>

</servlet>
<servlet-mapping>
  <servlet-name>ServletName</servlet-name>               
  <url-pattern>/aaa/xxx</url-pattern>                   <!--映射的url路径 -->

</servlet-mapping>

The configuration method of url-pattern:

  • Only when the resources accessed by an exact match are exactly the same as the configured resources can they be accessed
    insert image description here

  • Directory matching format: /virtual directory.../*, * stands for any
    insert image description here

  • Extension matching format: *.extension

insert image description here

Note: 1. Regarding the path, the greater the configured path matching range, the lower the priority; 2. Do not mix directory matching and extension matching, for example: /aaa/bbb/*.abcd (this is wrong)

ServletConfig object

ServletConfig encapsulates the configuration of servlet in web.xml.

For example, the web.xml parameter configuration is as follows:

<init-param>
    <param-name>name</param-name>
    <param-value>tom</param-value>
</init-param>

method:

//获得servlet的name(获得配置文件中<servlet-name>元素的内容)
String servletName =getServletConfig().getServletName();

//获取init-param中的所有参数(返回所有<param-name> )
Enumeration<String> en = getServletConfig().getInitParameterNames();
while(en.hasMoreElements()){
    
    
  String key = en.nextElement();
  //根据键获取值(根据<init-param>中的<param-name>获得</param-value>
  String value = getServletConfig().getInitParameter(key);)
  res.getWriter().print(key+"==>"+value+"<br/>");
}

Server startup instantiates Servlet configuration

When the Servlet is created: By default, it is created when it is accessed for the first time. Why is it the default? When adding a configuration to the servlet configuration, the servlet object is created when the server starts.

 <servlet>
    <servlet-name>abc</servlet-name>
    <servlet-class>com.itheima.servlet.QuickStratServlet</servlet-class>
    <init-param>
      <param-name>url</param-name>
      <param-value>jdbc:mysql:///mydb</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>abc</servlet-name>
    <url-pattern>/quickStratServlet</url-pattern>
  </servlet-mapping>

1. The load-on-startup element marks whether the container loads the servlet when it starts (instantiates and calls its init() method).

2. Its value must be an integer indicating the order in which the servlet should be loaded

3. When the value is 0 or greater than 0, it means that the container loads and initializes the servlet when the application starts;

4. When the value is less than 0 or not specified, it means that the container will load only when the servlet is selected.

5. The smaller the value of the positive number, the higher the priority of the servlet, and the earlier the application will be loaded when it starts.

6. When the values ​​are the same, the container will choose the order to load.

Therefore, <load-on-startup>x</load-on-startup>, the value of x in 1, 2, 3, 4, 5 represents the priority.

ServletContext object

ServletContext represents the environment (context) object of a web application. The ServletContext object internally encapsulates the information of the web application. There is only one ServletContext object for a web application. So how many servlet objects does a web application have? Many.

The life cycle of the ServletContext object

Create: The web application is loaded (the server starts or publishes the web application (if the server is started))

Destroyed: the web application is uninstalled (the server is shut down, and the web application is removed)

Get the ServletContext object

1ServletContext servletContext = config.getServletContext();

2ServletContext servletContext = this.getServletContext();

The role of ServletContext

1. Obtain the global initialization parameters of the web application, method:

getInitParameterNames();  ==> 获得所有键

getInitParameter(key);  ==> 根据键获得对应的值

For example: configure initialization parameters in web.xml

 <!--配置全局的初始化参数-->
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>

You can get the parameters through the context object

ServletContext context= getServletContext();
String initValue= context.getInitParameter("driver");
resp.getWriter().print(initValue);//com.mysql.jdbc.Driver

2. Obtain the absolute path of any resource in the web application

This feature is important. method:

getRealPath ==> Get the absolute path through the relative path
getResourceAsStream ==> Get the specified resource stream according to the relative path

3. ServletContext is a domain object

What are domain objects? What is a domain? The area where data is stored is the domain object.

The scope of the ServletContext domain object is the entire web application (all web resources can access data to the ServletContext domain at will, and the data can be shared)

域对象的通用的方法
放入键值对 setAttribute(key,value)
通过键取值 getAttribute(key)
通过键删除 removeAttribute(key)
遍历所有键 getAttributeNames()
//通过servletContext设置值
sc.setAttribute("bag", "Calvin Klein");
sc.setAttribute("car", "BMW");
sc.setAttribute("passport", "HAWAII");
//通过servletContext取值
String bag = (String) sc.getAttribute("bag");
//不喜欢,扔掉(删除)
sc.removeAttribute("bag");
//遍历
Enumeration<String> en = sc.getAttributeNames();
while(en.hasMoreElements()){
    
    
    String key = en.nextElement();
     Object value =  sc.getAttribute(key);
     System.out.println(key +"==>"+value);
}        

References:
1. https://www.cnblogs.com/ginb/p/7219259.html

Guess you like

Origin blog.csdn.net/weixin_42838061/article/details/121142406