JAVAWEB-Introduction to Servlet, Servlet API, Servlet xml configuration, ServletConfig object

1. Introduction to Servlet

  1. concept

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

  1. Servlet specification: contains three technical points
  • servlet technology
  • filter technology-filter
  • listener technology-listener

Two, Servlet API (life cycle)

  1. Servlet interface method
  • When is init(ServletConfig config)
    executed: it is executed when the servlet object is created. Some configuration information that we generally write in web.xml can be obtained in the init method.
    ServletConfig: Represents the configuration information of the servlet object
  • When service (ServletRequest request, ServletResponse response)
    is executed: every request will be executed
    ServletRequest : On behalf of the request, the ServletRequest encapsulates the http request information
    ServletResponse: On behalf of the response that the information to be encapsulated is the response
  • When destroy()
    is executed: executed when the servlet is destroyed
  1. Methods of HttpServlet class
  • init()
  • doGet(HttpServletRequest request,HttpServletResponse response)
  • doPost(HttpServletRequest request,HttpServletResponse response)
  • destroy()

3) Three questions for interview:

  • When Servlet was created
    The object is created when the servlet is accessed for the first time by default
  • When is the Servlet destroyed
    The servlet is destroyed when the server closes
  • Methods that must be executed every time you visit
    service(ServletRequest req, ServletResponse res)方法
    For the incoming parameters, please see the first information above for details.

Three, Servlet configuration

First we web.xmlwrite some commonly used things in

<servlet>
    <servlet-name>ASD</servlet-name>
    <servlet-class>servlet.QuickStartServlet</servlet-class>
    <init-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://sort</param-value>
    </init-param>
</servlet>
    <servlet-mapping>
        <servlet-name>ASD</servlet-name>
        <url-pattern>/quickStartServlet</url-pattern>
		<url-pattern>/aaa/bbb/ccc/*</url-pattern>

    </servlet-mapping>

Here to mention:The ASD in the servelt-name in the first servlet and the ASD in the servlet-name in the second servlet-mapping must be the same

1. Some precautions for configuration information:

1. <url-pattern></url-pattern>The matching method

a) Only when the resources accessed by the exact match are exactly the same as the configured resources can be accessed

<url-pattern>/quickStartServlet</url-pattern>

Standard access method

b) Directory matching format: /virtual directory.../ , where * represents any *

<url-pattern>/aaa/bbb/ccc/*</url-pattern

At this time, when we access a servlet in the browser, as long as we input the correct /aaa/bbb/ccc. You can enter whatever you want

c) Extension matching format: *. extension

<url-pattern>*.abcd</url-pattern>

At this time, when we access a servlet in the browser, we just need to input it in front of it. You can enter .abcd later

Note: Do not mix /aaa/bbb/*.abcd for the second and third types (wrong)

2. The server starts the instantiation Servlet configuration

First review: When was the
Servlet created: By default, it is created on the first visit.

If we need to add a configuration <load-on-startup>servlet object to be created when the server starts when the server is started, when the servlet is configured .

<!--servlet在服务器启动时创建对象-->
<!--数字代表优先级 数字越小 优先级越高-->
<load-on-startup>1</load-on-startup>

This is when we run the above QuickServlet again, when we have not entered the website, the init method is already running in the server.Because when the main server starts, the servlet has been created.

3. The default servlet

You can configure a / in url-pattern, which means that the servlet is the default servlet.
What is the default servlet?

When all the servlets in the address of your access resource do not match, the default servlet is responsible for processing
In fact, the response of all resources in the web application is servlet responsible, including static resources

4. Welcome page

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

By default, it will automatically access jsp and html files

2. How to obtain these configurations in Servlet?

public class QuickStratServlet implements Servlet{
    
    	
	@Override
	public void init(ServletConfig config) throws ServletException {
    
    
		
		//1、获得servlet的name----<servlet-name>ASD</servlet-name>
		String servletName = config.getServletName();
		System.out.println(servletName);//ASD
		//2、获得该servlet的初始化的参数
		String initParameter = config.getInitParameter("url");
		System.out.println(initParameter);
		//3、获得Servletcontext对象
		ServletContext servletContext = config.getServletContext();
		
		System.out.println("init running....");
	}
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    
    
		System.out.println("QuickStratServlet running....");
		res.getWriter().write("QuickStratServlet running....");
	}
	
	
	@Override
	public void destroy() {
    
    
		System.out.println("destroy running....");
	}
	@Override
	public ServletConfig getServletConfig() {
    
    
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String getServletInfo() {
    
    
		// TODO Auto-generated method stub
		return null;
	}
}

The output results areASDjdbc:mysql://sortinit running…

Four, ServletContext object

1. What is the ServletContext object
ServletContext represents the environment (context) object of a web application. The internal encapsulation of the ServletContext object is the information of the web application. The ServletContext object has only one
problem for a web application :

  • A web application has multiple servlet objects
  • The life cycle of the ServletContext object?
    Create: The web application is loaded (server starts or publishes the web application (prerequisite, server startup state).
    Destroyed: the web application is uninstalled (server shuts down, remove the web application)

2. How to get the ServletContext object

  • ServletContext servletContext = config.getServletContext();
  • ServletContext servletContext = this.getServletContext();

3. effect

  • Get the global initialization parameters of the web application.
    At this time, we are not configuring in the servlet, we are in the global

    Configure initialization parameters in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>WEB19</display-name>
  <!--配置全局的初始化参数-->
  <context-param>
  		<param-name>driver</param-name>
  		<param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
  
</web-app>

Then get the parameters through the context object

//获得ServletContext对象
ServletContext servletContext = getServletContext();
//1.获得初始化参数
String ininParamter = servletContext.getInitParameter("driver");
System.out.println(ininParamter);

The print result is: the content in param-value com.mysql.jdbc.Driver

  • Obtain the absolute path of any resource in the web application (important important)

Method String path = context.getRealPath(相对于该web应用的相对地址):;

Note that the path obtained here is relative to the project published to Tomcat.

Case : Create abcd.txt as shown in the figure. Get its absolute path separately
Insert picture description here

ServletContext servletContext = getServletContext();
    //获得a.txt
    String  realPath_A = servletContext.getRealPath("a.txt");
    //获得b.txt
    String  realPath_B = servletContext.getRealPath("WEB-INF/b.txt");
    //获得c.txt
    String  realPath_C = servletContext.getRealPath("WEB-INF/classes/c.txt");
    //d获取不到
    //读src(classes)下的资源是通过类加载器专门加载的
    ContextServlet.class.getClassLoader().getResource("d.txt").getPath();

Explain: Why is d.txt not found, because our publishing project is to publish the content under WEB-CONTENT, and d.txt is a file under the web project, not the content under WEB-CONTENT

  • ServletContext is a domain object (important important)

  • What is a domain object? What is a domain?
    The area where data is stored is the scope of the domain object
    ServletContext domain object: the entire web application (all web resources can freely access data in the servletcontext domain, and data can be shared)

    General methods of domain objects:
    setAtrribute(String name,Object obj);
    getAttribute(String name);
    removeAttribute(String name);

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/109143533