Servlet rapid development memory notes

1. What is Servlet

Servlet is a component of JavaEE and a specification in JavaEE.

Servlet is a specification in JavaEE: the server is actually the implementation of Servlet.
Servlet is a component of JavaEE: Servlet is a program (class), but it must follow the Servlet specification.

要求类:必须实现javax.servlet.Servlet接口.

2. How to build a JavaWeb project

Building a standard JavaWeb project structure::

1. Create a Java project: HelloServletWeb;
2. Create a folder webapp in HelloServletWeb, representing the root of the web project;
3. Create a WEB-INF folder in webapp,
4. Create a folder in WEB-IN: lib , classes
5. Go to Tomcat root/conf in WEB-IN and copy the web.xml file, just keep the root element.
6. Change the classpath path of the current project to classes under webapp/WEB-IN.

|-HelloServletWeb
|--webapp(这里可以写任何文件夹名,以后只需要将这个文件夹拷贝到服务器即可)
|---WEB-INF
|-----classes
|-----lib
|-----web.xml

3. Develop the first Servlet

Servlet belongs to the category of JavaEE and depends on the jar of JavaEE.

The first program writing steps of Servlet:
1): Copy the Tomcat root /lib/servlet-api.jar to the WEB-INF/lib directory of the project, and make a build path.
2): Write a servlet program to implement javax .servlet.Servlet interface, and override the methods in the interface.

    public class HelloServlet implements javax.servlet.Servlet{...实现方法...}

3): It is found that arg0 and arg1 appear in the parameters of the method because there is no source code associated with the Servlet.
Whether the source code is associated or not has nothing to do with the final operation of the program, but the parameters in the development stage are beautiful and
the source code can be read. Tomcat source code Program: apache-tomcat-7.0.57-src.zip

4): In the service(ServletRequest req, ServletResponse res) method, print a sentence.

5): At this time, the HelloServlet class has nothing to do with Tomcat: we need to tell Tomcat to help us manage the HelloServlet class. Deploy the project in server.xml:

<Context docBase="D:\JavaApps\Servlet\webapp" path="day3"/>

6): Configure the path for the resource

write picture description here

access:

http://ip:port/contextPath/资源名
http://localhost:80/day3/hello

4. Servlet life cycle

  1. Life cycle: from birth -> death, the process in between.
  2. Servlet life cycle: create object, initialize operation, run operation, destroy operation.
  3. Tomcat manages the life cycle of the servlet object, and the entire process of the servlet object is managed by Tomcat. The creation, initialization, operation, and destruction of the servlet are all called by Tomcat.

  4. Methods in the javax.servlet.Servlet interface:

    String getServletInfo():获取Servlet的信息(Servlet的作者,版本,版权相关).
    ServletConfig getServletConfig():获取Servlet的配置信息对象.
    
    void init(ServletConfig config):初始化Servlet对象方法
    
    void service(ServletRequest req, ServletResponse resp):服务方法,Web动态网页的操作就编写在该方法.
    
    void destroy():销毁Servlet对象方法.
    
  5. In the life cycle of the Web (Tomcat startup -> Tomcat shutdown), Servlets are singletons.

    构造器:在服务端程序第一次被请求的时候,调用,只被调用一次.
    
    void init(ServletConfig config):在构造器执行完毕之后,调用init方法,也只会执行一次.
    
    void service(ServletRequest req, ServletResponse resp):每一次请求都会执行该方法.
    
    void destroy():正常关闭Tomcat才会执行(该方法不一定会被执行,我们没必要在其中编写扫尾的操作).
    
  6. Summarize:

      构造器--->init方法---->[ service方法 ]循环 ---->destory方法
    

5. Servlet request process

1: The browser sends the request first: http://localhost:80/day3/hello .
2: DNS resolves the domain name (ignored)
3: Tomcat resolves the request: /day3/hello.
Context path: /day3
resource name: /hello
4: Parse the Tomcat root /conf/server.xml file, get all the elements in it, and find the element whose path attribute is /day3.

  <Context docBase="D:\JavaApps\Servlet\webapp" path="day3"/>

Then read the element, and then obtain the docBase attribute value, which is the root path of the currently accessed WEB project.

5: Find the web.xml file from the root path /WEB-INF of the web.
6: Read the web.xml file, get all the elements, and determine which one has the text content: /hello.

  找不到: 报404错误.
  找  到: GOTO 7.

7: Through /hello, find the fully qualified name of the current servlet.

 com._520it._01_hello.HelloServlet.

8: Get the object corresponding to com._520it._01_hello.HelloServlet from the instance buffer pool of Servlet.

  Map<String,Servlet> cache = .....;
  Servlet obj = cache.get("com._520it._01_hello.HelloServlet");
  if(obj == null{
       //第一次请求:GOTO 9.
  }else{
       //非第一次请求:GOTO 12;
  }

9: Use reflection to create a servlet object.

  Servlet obj = Class.forName("com._520it._01_hello.HelloServlet").newInstance();

10. Store the created servlet object in the servlet instance cache pool for the next request.

    cache.put("com._520it._01_hello.HelloServlet",obj);

11: The container creates a ServletConfig object and calls the init method to complete the initialization operation.

   obj.init(config);

12: The container creates ServletRequest and ServletResponse objects, and calls the service method to process the request.

   obj.service(req,resp);

13: In the service method, respond to the currently requested client.

6. Servlet initialization parameters

ServletConfig interface: Represents the information configuration object of the servlet (in web.xml, the configuration information of the current servlet).

Among the methods:

String getServletName():获取当前Servlet的名字,<servlet-name>元素的文本内容.

ServletContext getServletContext():获取当前的Servlet上下文,其实表示当前应用对象.

String getInitParameter(String paramName):根据当前Servlet的指定的参数名获取初始化参数值.

Enumeration<String> getInitParameterNames():获取当前Servlet的所有初始化参数的名字.

The configuration information is as follows:

<servlet>
    <servlet-name>ServletDemo2</servlet-name>
    <servlet-class>com._520it.servlet.ServletDemo2</servlet-class>
    <!-- 单个servlet的初始化数据 -->
    <init-param>
        <param-name>encoding</param-name>
        <param-value>GBK</param-value>
    </init-param>
    <init-param>
        <param-name>person</param-name>
        <param-value>lean</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>ServletDemo2</servlet-name>
    <url-pattern>/servletdemo2</url-pattern>        
</servlet-mapping>

Get initialization parameters:

write picture description here

7. Servlet inheritance system

The following simulates the Servlet inheritance system. First, Servlet is an interface specification, and Tomcat implements two subclasses, GenericSevlet and HttpSevlet.

MyGenericSevlet.java

/**
 * 该类主要封装了ServletConfig对象的业务逻辑
 */
public abstract class MyGenericSevlet 
    implements Servlet,ServletConfig,Serializable{

    private static final long serialVersionUID = 1L;
    protected ServletConfig config;

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

    public void init() {
        //NO OP
    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }

    @Override
    public String getServletInfo() {
        return "";
    }

    @Override
    public void destroy() {

    }

    //---------如下就是ServletConfig 接口对应的方法--------
    @Override
    public String getServletName() {
        return config.getServletName();
    }

    @Override
    public ServletContext getServletContext() {
        return config.getServletContext();
    }

    @Override
    public String getInitParameter(String name) {
        return config.getInitParameter(name);
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
        return config.getInitParameterNames();
    }

}

MyHttpSevlet.java:

/**
 * 该类主要封装了Http对象相关的请求方法
 */
public abstract class MyHttpSevlet  extends MyGenericSevlet{

    @Override
    public void service(ServletRequest req, ServletResponse res) 
            throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) res;
        service(request, response);
    }

    public void service(HttpServletRequest req, HttpServletResponse res) 
            throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equals("GET")) {
            doGet(req, res);
        }else {
            doPost(req, res);
        }
    }

    private void doPost(HttpServletRequest req, HttpServletResponse res) {
        //DEFAULT IMPL
    }

    private void doGet(HttpServletRequest req, HttpServletResponse res) {
        //DEFAULT IMPL
    }

}

Summarize:

write picture description here

8. Common methods of HttpServletRequest

ServletRequest interface: The request object, which encapsulates the method of obtaining all request information (request line, request header, request entity).
HttpServletRequest interface: It is a sub-interface of ServletRequest and handles HTTP protocol requests.
Common methods:

01.String getMethod():返回请求方式:如GET/POST
02.String getRequestURI():返回请求行中的资源名字部分:如/test/index.html

03.StringBuffer getRequestURL():返回浏览器地址栏中所有的信息
04.String getContextPath():返回当前项目的上下文路径(<Context/>元素的path属性值.)
05.String getRemoteAddr():返回发出请求的客户机的IP地址
06.String getHeader(String name):返回指定名称的请求头的值。

How to get request parameters:

01.String getParameter(String name):返回指定名字参数的值。

02.String[] getParameterValues(String name):返回指定名字参数的多个参数值。

03.Enumeration<String> getParameterNames():返回所有参数名的Enumeration对象。

04.Map<String,String[]> getParameterMap():返回所有的参数和值所组成的Map对象。

9. Common methods of HttpServletResponse

ServletResponse interface: Response object. It encapsulates the method of obtaining response information.
HttpServletResponse interface: a sub-interface of ServletResponse, which can process HTTP response methods.

Common method:

OutputStream getOutputStream():获取字节输出流对象.  文件下载.
PrintWriter  getWriter():获取字符输出流对象
注意:上述方法,不能共存,否则报错.

Set the output MIME type (content type):
response.setContentType("text/html");//Can't write wrong
Set the encoding method of output data:
response.setCharacterEncoding("UTF-8");
You can use the above two lines The code is combined into one line of code:
response.setContentType("text/html;charset=utf-8");

Note: MIME type and encoding must be set before getting the output stream, otherwise it will have no effect.

10. Servlet Mapping Details

1): A servlet program (web component) can be configured with multiple, indicating that a servlet has multiple resource names.
2): A servlet program can be configured with multiple.
3): must ensure uniqueness, and must use / at the beginning .
4): Servlet mapping supports wildcard mapping (*: represents any character):

 第一种写法:   /*,任意的资源都可以访问该Servlet. /system/*:请求的资源必须以/system/打头才可以访问.
                Servlet中,权限控制:
  第二种写法:   *.拓展名, 比如: *.do,请求的资源必须以.do作为结尾才可以访问该Servlet.

5): When mapping servlets, the text content of elements cannot be default. Because there is a servlet called default in Tomcat, which is specially used to process requests for static resources (html, css, js, pictures, etc.).
In the Tomcat root /conf/web.xml file:

<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
        ...
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

11. Servlet3.0 new features - annotation configuration

Servlet3.0 corresponds to the JavaEE6 specification, Tomcat7.*.

Problem: Traditionally, XML is used for servlet configuration. If there are N servlets, 10*N lines of code must be configured, and the web.xml file is bloated, which is not conducive to maintenance and low development efficiency.

Starting from Tomcat7, you can use annotations (WebServlet) to replace XML configuration.
Note: In the root element of the web.xml file, there is an attribute indicating whether to ignore scanning Web components annotations:
metadata-complete=”true” : to ignore
metadata -complete=”false”: don’t ignore
don’t change attribute: the default is equivalent to metadata-complete=”false”.

Development steps:

1. Modify web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" metadata-complete="false">
  ...

 </web-app>

2. In the servlet, configure it:

@WebServlet(value="/mapping",loadOnStartup=1,
    initParams= {@WebInitParam(name="encoding",value="GBK"),
            @WebInitParam(name="username",value="lean")})
public class MappingServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("mapping service !");
        String encoding = getInitParameter("encoding");
        String username = getInitParameter("username");
        System.out.println(encoding+"  "+username);
    }

}

12. Start the initialization servlet

Review the execution process of the servlet life cycle method:
when starting the Tomcat server, there is no servlet creation and initialization operation.
At the first server request:
1): create a servlet object.
2): call the init method for initialization.
3): Call the service method to process the request.

If one day, a servlet (core servlet: initialization global information) needs to be created when the server is started, we can use the loadOnStartup configuration.

After configuration, start Tomcat, you will find that init is called, but it does not mean that the service is called, because we just created the object and did not call the components of the object.

13. Servlet thread safety issues

Thread insecurity of servlets:

The root cause is: Servlet is a singleton, there is only one non-static member variable in Servlet, multiple clients are like multiple threads, and they all access the same space.
Solution:

     1:让当前Servlet实现javax.servlet.SingleThreadModel接口.
       包装只有一个线程放Servlet,如果有多个线程就排队,如此的话,性能超低(已过时).
     2:在Servlet中不要使用成员变量,使用局部变量.
       每一个用户,每一个请求都会调用service方法,而局部变量在service方法中,每一次都是新的空间.

Struts1 and Spring MVC are both thread-unsafe and singletons are similar to Servlets.
Struts2 is thread-safe because each thread (request) is a new Action object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325985938&siteId=291194637