Servlet technologies - overview, implementation details, access to resources, ServletConfig, ServletContext

Servlet overview, implementation details, access to resources, ServletConfig, ServletContext

(A) Setvlet basic overview

(1) What is Servlet?

Servlet (Server Applet) is JavaServlet short, called the small connector service programs or services, written in Java Server-side program, with a platform-independent and protocol features, the main function is to interactively browse and generate data, generate dynamic Web content is

JavaWeb we will contact the three components (Servlet, Filter, Listener), Servlet invoked by the server, the server receives the processing request is completed, receiving the request data -> Request Processing -> completion response, the nature of a java class that implements the Servlet interface

Servlet class written by us, but the object is created by the server, and to call the appropriate method by the server

(2) Servlet used to do?

Some of the more common network functions such as login, registration, interactive features such exist, and Servlet can help us deal with these requests, it can be said Servlet JavaWeb knowledge is one of important points

(B) a way to achieve Servlet

There are three ways to achieve Servlet:

  • Javax.servlet.Servlet implement the interface;
  • Javax.servlet.GenericServlet inherited class;
  • Javax.servlet.http.HttpServlet inherited class;

The actual development, we often choose to inherit the HttpServlet class to complete our Servlet, Servlet interface but recognized in this way is also very important, it is our indispensable part of getting started

(1) create our first Servelt

We create a web project, select the corresponding parameters, we installed the jdk version 1.8, you can choose to JavaEE8 version 4.0 is the corresponding versions, but here we are still quite a lot on the market with a choice of version 7

Demo create a class that implements the Servlet interface, and then we quickly generating methods in this interface is not implemented, we first Servlet methods ignore the other four, only care about service () method, because it is the method used to process the request, we the output statement within a given method

package cn.ideal.web.servlet;

import javax.servlet.*;
import java.io.IOException;

public class ServeltDemo1 implements Servlet {
    //初始化方法
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    }

    //Servlet配置方法
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    //提供服务方法
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("理想二旬不止");
    }

    //Servlet信息方法
    @Override
    public String getServletInfo() {
        return null;
    }

    //销毁方法
    @Override
    public void destroy() {
    }
}

It finished a simple Servlet code, but how can access to it in a browser? We need to configure web.xml in web / WEB-INF, we <web-app></web-app>add the following code (although there are ways to optimize the latter, but it is recommended that you memorized)

<servlet>
        <!--给这个Servlet起一个名字,一般与类名相同-->
        <servlet-name>ServletDemo1</servlet-name>
        <!--全类名-->
        <servlet-class>cn.ideal.web.servlet.ServeltDemo1</servlet-class>
    </servlet>

    <!--配置映射路径-->
    <servlet-mapping>
        <servlet-name>ServletDemo1</servlet-name>
        <!--外界访问的路径-->
        <url-pattern>/Demo1</url-pattern>
    </servlet-mapping>

Now we are in our url-patternpath to access the configuration of the look, and sure enough in the console output, ideal binary string more than ten days

Effect (2) web.xml of

Build on the progress we simply analyze the causes of this web.xml, in fact, in web.xml configuration purposes of Servlet , is to put in the browser's access paths corresponding Servlet tied together , the above example is the access path: "/ Demo1" and "cn.ideal.web.servlet.ServeltDemo1" to bind together

1 <servlet></servlet>: Specifies the name of the Servlet ServletDemo1 ServletDemo1, corresponding to the general class of the same name here

2, <servlet-mapping></servlet=mapping>: set the access path to the specific

Both of which passed <servlet-name></servlet-name>associate together

Implementation process:

1, when the server receives a request from the browser parses the URL path, to get the resource path Servlet

2, find the web.xml file, find the <url-pattern>label, look for the full class name corresponding<servlet-class>

3, Tomcat bytecode file is loaded into memory, and creates an object, wherein the method invocation

So we need to know: Most of the methods in Servlet not be created and called by us, by the completion of Tomcat

(C) Servlet Interface

(1) a brief overview of the life cycle

I will simply understood as the life cycle of several processes:

During his lifetime - Born - Services - death - burial

1, during his lifetime: when the first visit Tomcat Servlet, Tomcat will create an instance of the Servlet

2, was born: Tomcat will call the init () method to initialize the object

3, the service: when the client access Servlet, service () method is called

4. Death: When Tomcat Servlet is turned off or not used for a long time, destroy () method is called

5, bury: after destroy () method is called, Servlet to wait for garbage collection (not easy), there is need to use the init () method to re-initialize

(2) Detailed life cycle

1, during his lifetime

S server at the time ervlet first accessed , or at server startup to create a Servlet. If you create a server startup Servlet, you also need to be configured in the web.xml file, which means that by default, Servlet is created by the server at the time of the first visit

A Servlet type, the server creates only one instance of the object: for example, the first time we visit <http://localhost:8080/Demo1>, the server /Demo1to find cn.ideal.web.servlet.ServeltDemo1, the server will determine whether this type of Servlet been created, if not only to create an instance of ServletDmoe1 by reflection, or directly examples of the use of already existing

2, born

After Servlet is created, the server will immediately call the Servlet void init(ServletConfig)methods, but a Servlet life, this method can only be called once, we can put some work into the initialization of the Servlet methods!

3, Service

When the server each time it receives a request, are to call the service Servlet () method to process the request. service () method will be called multiple times, the server receives a request, it will call the service () method once, because of this, so we need to write the code that handles requests service (method)!

4, death and burial

When the server is closed Servlet also need to be destroyed, but before the destruction, the server will first call the Servlet destroy () method, we can put some code to release resources to the here

Type three (3) Servlet interface

In these five methods, we can see three types we have not been in contact in the parameters

public void init(ServletConfig servletConfig) throws ServletException {}

public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {}

That is, the three types: ServletConfig, ServletRequest, ServletResponse

A:ServletConfig

ServletConfig is an object created by the server, and then passed to the Servlet init (method)

We simply use the following methods at first getServletName () on it, the back of the methods we learn to write a Context, and other knowledge to better understand

//获取Servlet在web.xml文件中的配置名称,即<servlet-name>指定的名称
String getServletName()

//用来获取ServletContext对象
ServletContext getServletContext()

//用来获取在web.xml中配置的初始化参数,通过参数名来获取参数值;
String getInitParameter(String name)

//用来获取在web.xml中配置的所有初始化参数名称
Enumeration getInitParameterNames()

B:ServletRequest & ServletResponse

These two types appear in the Servlet service () method, representing the request and response objects, and examples of both are also created by the server

But we want to do a web application, and ultimately be linked to HTTP, if we want to use HTTP methods related functions in service (), can turn into a strong ServletResponse ServletRequest and HttpServletRequest and HttpServletResponse

HttpServletRequest方法:

//获取指定请求参数的值;
String getParameter(String paramName)

//获取请求方法,例如GET或POST
String getMethod()
    
//获取指定请求头的值;
String getHeader(String name)

//设置请求体的编码!
/*
    GET没有请求体,所以这个方法只只对POST请求有效当调用
    这个方法必须在调用getParameter()方法之前调用!
    使用request.setCharacterEncoding(“utf-8”)之后,再通过getParameter()方法获取参数
    时,参数值都已经通过了转码,即转换成了UTF-8编码
*/
void setCharacterEncoding(String encoding)

HttpServletResponse方法:

//获取字符响应流,使用该流可以向客户端输出响应信息。
PrintWriter getWriter()
Eg:response.getWriter().print(“<h1>Just for test</h1>”);
    
//获取字节响应流,例如可实现向客户端响应一张图片
ServletOutputStream getOutputStream()

//用来设置字符响应流的编码
void setCharacterEncoding(String encoding)
   
//向客户端添加响应头信息
void setHeader(String name, String value)
Eg:setHeader(“Refresh”, “3;url=http://www.xxx.com”) 表示三秒后自动刷新到该网址

//该方法是setHeader(“content-type”, “xxx”)的简便方法,即用来添加名为content-type响应头的方法
/*
    content-type响应头用来设置响应数据的MIME类型,例如要向客户端响应jpg的图片,那么
    可以setContentType(“image/jepg”),如果响应数据为文本类型,那么还要台同时设置编
    码,例如setContentType(“text/html;chartset=utf-8”)表示响应数据类型为文本类型
    中的html类型,并且该方法会调用setCharacterEncoding(“utf-8”)方法;
*/
void setContentType(String contentType)
    
//向客户端发送状态码,以及错误消息
void sendError(int code, String errorMsg)

(D) GenericServlet class

A: can know by looking at the source code of this class, the class only

public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

Need to implement a method , other methods have already been defined in the source code

B: GenericServlet's init () method

Also we need to mention the two methods mentioned is

public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

public void init() throws ServletException {
}

GenericServlet class implements the Servlet's init (ServletConfig) method, the config parameters assigned to the members of the class config, then call this class of its own no-argument init () method

This method is GenericServlet own method, rather than inherited from Servlet down. When our custom Servlet, if you want to complete the initialization action would not have to repeat the init (ServletConfig) method, but rather should go to override the init () method. Because GenericServlet in the init (ServletConfig) ServletConfig object save method, if the code is stored ServletConfig covering, then you can not use the ServletConfig

C: implements the interface ServletConfig

GenericServlet also implements ServletConfig interfaces , so you can directly call getInitParameter (), getServletContext () methods of ServletConfig.

But this is not our class we still talk about focus, we then look at the next class

(E) HttpServlet class

(1 Overview

In the above we realize Servlet interface need to implement five methods, very troublesome, and HttpServlet class has achieved all Servlet interface methods, the preparation of Servlet, need only to extend HttpServlet, you need to override the method, and it provides for special support HTTP requests , more powerful

(2) service () method

HttpServlet in the service(ServletRequest,ServletResponse)process will ServletRequest and ServletResponse strong turn into HttpServletRequest and HttpServletResponse

//HttpServlet 源码节选
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)res;
        } catch (ClassCastException var6) {
            throw new ServletException("non-HTTP request or response");
        }

        this.service(request, response);
    }

After strong turned, then call HttpServlet class provides service(HttpServletRequest,HttpServletResponse)methods, this is the class method itself , rather than inherited, suggesting that when we use, only need to cover service(HttpServletRequest,HttpServletResponse)it, do not need to be strong turn this the two objects

Note: In fact, there are even more simplified step by step, do not use service(HttpServletRequest,HttpServletResponse)

(3) doGet () and doPost ()

In the HttpServlet service(HttpServletRequest,HttpServletResponse)method will be to judge the request is a GET or POST, if a GET request, went to call the class doGet () method, if it is a POST request, went to call the doPost () method, which shows us in a subclass to cover doGet () or doPost () method can be a

(Vi) Servlet details

(1) thread-safety issues

Servlet server will only be to create an instance of an object, in many cases, a Servlet need to handle multiple requests, it is clear, though Servlet high efficiency, but not thread-safe

So we should not easily create member variables in the Servlet, because there may be multiple threads at the same time the members of the different operating variables

Conclusion: Do not establish membership in a Servlet in! To create a local variable, the amount of a member can be created stateless, or status read only member

Servlet is created when (2) server starts

Before we would have said that when the life cycle, Servlet is created when you first accessed by the server, but we can configure the Servlet in web.xml, so that when the server starts to create a Servlet

<servlet>
    <servlet-name>ServletDemo1</servlet-name>
    <servlet-class>cn.ideal.web.ServletDemo1</servlet-class>
     <!--在<servlet>中配置<load-on-startup>,其中给出一个非负整数!-->
    <load-on-startup>0</load-on-startup>
</servlet>

Its role is to determine the order of creation Servlet server startup

(3) a Servlet can bind multiple URL

<servlet-mapping>
    <servlet-name>Servlet</servlet-name>
    <url-pattern>/AServlet</url-pattern>
    <url-pattern>/BServlet</url-pattern>
</servlet-mapping>  

After such configuration regardless of access / AServlet or / BServlet, access is AServlet

(4) wildcard matching problem

In <url-pattern>wildcards can be used, that is, "*", it can match any prefix or suffix

<!--路径匹配-->
<url-pattern>/servlet/*<url-patter>:/servlet/a、/servlet/b,都匹配/servlet/*;

<!--扩展名匹配-->
<url-pattern>*.xx</url-pattern>:/abc/de.xx、/a.xx,都匹配*.xx;

<!--什么都匹配-->
<url-pattern>/*<url-pattern>:匹配所有URL;

Wildcard either as a prefix or suffix can not appear in the URL intermediate position, and a URL in a wildcard can only occur if there is a more specific address, priority access to a specific address

(七) ServletContext

(1 Overview

The server will create a web application for each ServletContext object, it can be said that it represents the web site, and this object, it is created when Tomcat starts, will be destroyed when Tomcat shutdown

(2) Function

All Servlet share with a ServletContext object, so the role of ServletContext object is shared between dynamic resource data in the entire Web application, you can communicate via ServletContext that is different between the Servlet, thereby sharing data

(3) get ServletContext object

There GetServletContext of GenericServlet () method, can be used directly this.getServletContext () to obtain

public class MyServlet implements Servlet {
    public void init(ServletConfig config) {
        ServletContext context = config.getServletContext();
    }
}
public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        ServletContext context = this.getServletContext();
    }
}

(4) the function of the object field

All objects have a way to access the domain data function, this embodiment can be seen as storing data, Map of

The method of operation of several common data to look at us

storage

//用来存储一个对象,也可以称之为存储一个域属性
void setAttribute(String name, Object value)
    
Eg:servletContext.setAttribute(“xxx”, “XXX”)
//在ServletContext中保存了一个域属性,域属性名称为xxx,域属性的值为XXX

Obtain

//用来获取ServletContext中的数据
Object getAttribute(String name)
//获取名为xx的域属性
Eg:String value = (String)servletContext.getAttribute(“xxx”);


//获取所有域属性的名称;
Enumeration getAttributeNames()

Remove

//用来移除ServletContext中的域属性
void removeAttribute(String name)

Visits statistics of small case

package cn.ideal.web.servlet;

import javax.servlet.*;
import java.io.IOException;

public class ServletDemo2 extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext servletContext = this.getServletContext();
        //获取ServletContext对象中的count属性
        Integer count = (Integer) servletContext.getAttribute("count");
        if (count == null) {
            //如果在ServletContext中不存在count属性,name设置为count的值为1,表示第一次访问
            count = 1;
        } else {
            //如果在Servlet中存在count属性,说明以前被访问过,name让count在原来的基础上加1
            count++;
        }
        servletResponse.setContentType("text/html;charset=UTF-8");
        //向客户端响应本页面被访问的次数
        servletResponse.getWriter().print("<h1>本页面一共访问" + count + "次</h1>");
        //保存count的值到ServletContext对象中
        servletContext.setAttribute("count", count);
    }
}

(Viii) access to resources related methods

(1) Get the path

Use ServletContext object can be used to access resources in Web applications, such as creating aaa.txt file in the root directory of a web application, create bbb.txt file under WEB-INF directory, if we want to get both by the Servlet I would write path

//获取aaa.txt的路径
String realPath = servletContext.getRealPath(“/aaa.txt”)

//获取bbb.txt的路径
String realPath = servletContext.getRealPath(“/WEB-INF/b.txt”)

Gets a single file path is the case, there is a way we can get to all the resources specified directory path, such as access to all resources under the path / WEB-INF

Set set = context.getResourcePaths("/WEB-INF");
System.out.println(set);

(2) access to resources flow

Not only can we use ServletContext get the path, we can also get the flow of resources to assume the above two documents, for example

//获取aaa.txt
InputStream in = servletContext.getResourceAsStream(“/aaa.txt”);

//获取bbb.txt
InputStream in = servletContext.getResourceAsStream(“/WEB-INF/b.txt”);

The resources (3) Get classpath

InputStream in = this.getClass().getClassLoader().getResourceAsStream("xxx.txt");
System.out.println(IOUtils.toString(in));

(Ix) the use of annotations, is no longer configured web.xml

Each create a Servlet we need to configure in web.xml, but if our Servlet version 3.0 or higher, you can choose not to create web.xml, and uses annotations to solve, very simple and convenient

For example, we create a Servlet, web.xml configuration as follows

<servlet>
    <servlet-name>ServletDemo2</servlet-name>
    <servlet-class>cn.ideal.web.servlet.ServletDemo2</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ServletDemo2</servlet-name>
    <url-pattern>/Demo2</url-pattern>
</servlet-mapping>
//在类名的上方写入这样一句代码,引号内为外部访问路径
@WebServlet("/Demo2")

Is not very easy, we look at the principles involved:

//WebServlet 源码节选
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebServlet {
    String name() default "";

    String[] value() default {};

    String[] urlPatterns() default {};

    int loadOnStartup() default -1;

This annotation can be seen, @Target({ElementType.TYPE})the scope for the class, @Retention(RetentionPolicy.RUNTIME)remain in the runtime, name () method but here not so important, because in the web.xml, name functions primarily as an association, in which the most important thing is that we String[] urlPatterns() default {};Configuring an address, which is defined as an array, of course, a configuration is also possible, that is, urlPatterns = "/Demo2"of which the most important value represents value, in fact, also on behalf of this address, it can be written as Value = "/Demo2", and value and can be omitted, so you can written"/Demo2"

end:

If there are any deficiencies, or content in the wrong place, welcome to give me a shout advice, crab everyone! ^ _ ^

If you can help, then it is to pay attention to me! (Updated series of articles will be the first time the public number)

Here we are strangers, all in the dream and work for their own ❤

Push a stick original Java technology public numbers: more than ten days over two

Guess you like

Origin www.cnblogs.com/ideal-20/p/11407196.html