Servlet

巴扎黑
巴扎黑Original
2017-06-23 16:31:252049browse

Overview

1. Server

All factors that process requests and give responses The whole thing is called a server, which includes hardware and software.

2. Servlet specification

The principles that the server follows when processing requests and responding.

3.What is Servlet?

Server Applet, a Java application running on the server side, is written in Java language and complies with the Java specification, the core of the Servlet specification.

4. The status of Servlet in the Web server

Servlet plays the role of controller in the entire Web server, forwarding requests to the corresponding business logic processing.

5.What is tomcat?

Tomcat is the software aspect of the server. It is a container that implements the Servlet specification and the JSP specification. It is a lightweight, free, open source code provided by Apache. Application server is suitable for small and medium-sized systems and situations where there are not many concurrent access users.

6.MIME

Multipurpose Internet Mail Extensions, a multipurpose Internet mail extension protocol, develops a specification for each type of file So that

the browser will call the corresponding component to open after receiving the file.

Two important categories

1.ServletContext

  • ServletContext, Servlet context, is the environment in which the Servlet used exists, a Web application, an instance object, which works at the entire application

    level.

  • JSP built-in object application is a ServletContext instance,

  • ServletContext corresponds to the file Based on web.xml, web.xml contains all user-defined information in the entire server. From this, we can see the scope of

    ServletContext.

  • Function: ServletContext is mainly used to load various components to the server when the Web server starts, and initialize the server according to custom parameters.

  • Life cycle: The ServletContext object is created when the server starts and is destroyed when the server stops.

Important methods:

servletContext.setAttribute(name, object);//向servletContext作用域中添加属性,该属性为所有用户共享servletContext.getAttribute(name);//获取servletContext作用域中指定属性的属性值servletContext.removeAttribute(name);//从servletContext作用域中删除指定属性servletContext.getRealPath(path);//根据相对于项目的路径获取资源的绝对路径URLservletContext.getResourceAsStream(path);//获取路径文件的输入流servletContext.getInitParameter(name);//获取初始化参数的值

Object acquisition:

The ServletContext object is automatically created by the Web server when it starts. All the programmer needs to do is to obtain the instance object. The following are several

obtaining methods.

this.getServletContext();//HttpServlet提供了获取ServletContext实例对象的方法,在doGet或者doPost方法内部request.getServletContext();//通过request对象获取HttpSession session = request.getSession();
session.getServletContext();//通过session对象获取
2.ServletConfig

is used to initialize Servlet, one Servlet, one ServletConfig.

public void init(ServletConfig config) throws ServletException {
String initParameter = config.getInitParameter("initParamName");
}

 

三 Servlet

1.Servlet的工作原理:

Web容器启动时会创建两个与Servlet相关的Map集合,两个集合的key值均为urlPattern,即请求uri,第一个Map的value是Servlet的引用变量,第二个Map的value是Servlet的全限定性类名。请求到达Web容器后,系统先搜索第一个Map集合,如果存在与uri对应的引用变量,则获取该引用变量,如果不存在,继续搜索第二个Map集合,获取对应的全限定类型,创建对象,并把引用变量存到第一个Map集合中。

2.Servlet继承结构

                                                             
                                    Servlet                 ServletConfig              Serializable
                                         |                               |                               |
                                         --------------------------------------------------
                                                                         |
                                              GenericServlet
                                                                         |
                                                  HttpServlet

  3.实际开发中Servlet的创建方式

   Servlet接口是Servlet规范中定义的,服务器自动调用其中service方法处理请求,该接口有多个抽象方法,很多在实际开发中很少使用,实现该接口需要实现其中的全部抽象方法,因此不采用直接实现Servlet接口的方法创建Servlet。

    GenericServlet实现Servlet接口中大多数抽象方法,保留了一个抽象方法service,继承该抽象类创建servlet,必须实现该抽象方法。HTTP中多个请求方法在处理请求前必须做一些固定的前置工作,如果实现该serivce方法就需要在每一个Servlet的service方法中都编写前置工作代码,造成代码冗余。为了解决此问题,tomcat提供了一个GenericServlet的子类HttpServlet,HttpServlet采用固定行为结构的模板方法模式将前置工作固定在一个方法,用户在创建Serlvet时继承HttpServlet,然后重写与请求方式对应的方法即可。(具体参考源码)

HttpServlet源码

protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

        String method = req.getMethod();if (method.equals(METHOD_GET)) {long lastModified = getLastModified(req);if (lastModified == -1) {// servlet doesn't support if-modified-since, no reason// to go through further expensive logic                doGet(req, resp);
            } else {long ifModifiedSince;try {
                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                } catch (IllegalArgumentException iae) {// Invalid date header - proceed as if none was setifModifiedSince = -1;
                }if (ifModifiedSince < (lastModified / 1000 * 1000)) {// If the servlet mod time is later, call doGet()// Round down to the nearest second for a proper compare// A ifModifiedSince of -1 will always be less                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

        } else if (method.equals(METHOD_HEAD)) {long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);

        } else {//// Note that this means NO servlet supports whatever// method was requested, anywhere on this server.//String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsg, errArgs);

            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
        }
    }

从中可以看出Get请求在实际执行前做了很多准备工作。

4.生命周期

Servlet默认在调用时创建并初始化,这也是工作原理中第一个Map集合引用变量为空情况出现的原因。对一些必定会被访问并且访问频繁的Servlet可以设定为在容器启动时创建并初始化,提高访问速度。

<load-on-startup>int类型数字</load-on-startup>

小于0:默认值,调用时创建初始化。
    等于大于0:在Web服务器启动时创建初始化,值越小,优先级越高。出现相同值时,不会出现异常,容器自定义顺序执行。

     5.主要方法:

this.getInitParameter("");//获取初始化参数this.getServletName();//获取配置文件<servlet-name>标签的内容this.getServletContext();

6.由于继承HttpServlet创建的Servlet属于自定义类,系统不知晓,必须在配置文件中配置:

<servlet>     <servlet-name>bothRegisterServlet</servlet-name>     <servlet-class>com.servlet.register.BothRegisterServlet</servlet-class>     <init-param>         <param-name>xxx</param-name>         <param-value>xxxx</param-value>     </init-param>     <load-on-startup>1</load-on-startup>     <async-supported>true</async-supported></servlet><servlet-mapping>     <servlet-name>bothRegisterServlet</servlet-name>     <url-pattern>/bothRegisterServlet01</url-pattern></servlet-mapping>

When accessing the Servlet object in the Web container, no matter which method is used, it can only be accessed indirectly. Generally, url is used to access the servlet, so you need to The url used when accessing is the same as the final one. A one-to-one mapping relationship is established between resource servlets, which is why servletMapping exists.

Allows multiple url formats to be configured for a Servlet object.

Four request

1. What is request?

Servlet specification definition An object that provides client request information to the Servlet.

2. What information is included in the request, or what information can be obtained through the request?

  • Request parameters: When the form input is empty, the content obtained by the server is an empty string, not null.

  • Attributes within the request scope: Data can be stored in the request scope and obtained in the same request.

  • Input stream: When uploading a file, you can obtain the input stream of the uploaded file through request.

  • Cookie: Cookie is generated by the server, saved in the client list, and automatically submitted when the browser makes a request to the server.

  • #Part: The object representing the uploaded file.

  • #Other built-in objects: such as session\application.

  • Other information closely related to the request: such as request method, browser used, protocol, request url, request body length, query string, request header , client IP, port number, etc.

3. Commonly used methods:

⑴Comparison between request.getParameter() and request.getAttribute()

  • getParameter: Get the value of the request parameter, and return the value String. When the form input is empty, the return value is an empty string, not null.

  • getAttribute: Get the attribute within the scope. The return type is the attribute type. When the attribute does not exist, null is returned.

⑵request.getSession() and request.getSession(boolean create) comparison

  • getSession(): Same as getSession(true), obtains the Session object based on Cookie. If the Cookie does not exist, create a new session.

  • getSession(false): Get the Session object based on Cookie. If the Cookie does not exist, return null.

⑶request.setCharacterEncoding(): Set the encoding method of the request body, that is, the encoding method used by the server when parsing the data submitted by the browser. Since only the data of the POST request is transmitted through the request body, it is only meaningful for the POST request and has no meaning for the GET request.

⑷request.getContentLength(): Gets the byte length of the request body, which is only meaningful for POST.

⑸request.getQueryString(): Gets the request string after the URL, which is only meaningful for GET requests.

⑹The difference between request.getRequestDispatcher().forward(request,response)request.getRequestDispatcher().include(request,response):

The resources holding the response right are different:

  • forward will continue to push the request forward and transfer the response right to the subsequent resources. It cannot send a response to the server itself. , that is, using the out.write method in itself cannot output content to the page.

  • include includes, treating the following resources as part of itself. Not only the following resources can respond, but it can also respond, which is equivalent to making one of its ownPart of the code is divided into the following resources.

# 4. What is the same request?

Before a request ends, if no redirection operation is performed, forwarding and inclusion operations are performed, it still belongs to the category of the same request.

5. The meaning of the same request

The same request shares information such as request parameters and attributes in the scope.

五 response

1.什么是response?

Servlet规范定义的一个向浏览器发出响应的对象,由Servlet容器自动创建。

2.reponse主要作用:

⑴设置响应的MIME类型及编码方式。

由于存在多种响应数据类型,因此服务器在响应前必须指明数据类型,以便浏览器根据指定类型处理接收的数据。

response.setContentType("text/html;charset=UTF-8");//以HTML方式处理

⑵设定响应头,即响应内容的其他方面:

response.setHeader(name,value);

⑶创建并将Cookie保存到客户端:

response.addCookie(Cookie cookie);

⑷重定向:

response.sendRedirect(url);

⑸获取向浏览器输出内容的输出流:

PrintWriter out=reponse.getWriter();

⑹获取文件下载的输出流:

ServletOutputStream sos=response.getOutputStream();

3.响应或者跳转后的代码执行问题

代码继续执行,对响应结果或者request作用域没有影响,因为响应已经结束,请求已转发给其他资源,自身就失去了处理请求的能力,但对session\applicatiion作用域可以产生影响。通常不在响应或者跳转之后对整个处理过程施加影响。

六 Cookie

1.什么是Cookie?

由服务器生成,保存在浏览器端的存储会话信息的对象。

2.创建Cookie

Servlet规范提供了Cookie类,用于创建Cookie对象:

Cookie cookie=new Cookie(name,value);

3.保存Cookie

由服务器创建,保存在客户端,浏览必须允许保存Cookie将cookie:

response.addCookie(cookie);

4.设定Cookie路径:

Cookie在访问服务器时自动提交,这种提交不是无选择地对任何访问路径都提交,而是只对设定的路径提交。在未单独设定Cookie的绑定路径时,Cookie与生成Cookie的访问路径绑定,访问该路径下任何一个资源时,浏览器自动提交Cookie。
    可以设定Cookie的绑定路径,使Cookie不受生成路径的限制:

cookie.setPath(String uri);

5.Cookie的生命周期

默认情况下,Cookie保存在浏览器缓存中,浏览器关闭,Cookie销毁。如果希望Cookie中保存的信息长期存在,可以将Cookie保存到本地硬盘中,前提是当前浏览器支持。

cookie.setMaxAge(int expiry);//以秒为单位
  • 取值大于0:将Cookie保存到硬盘中,无论浏览器是否关闭,指定时长过去后,Cookie被销毁。

  • 等于0:立即销毁Cookie。

  • 小于0:默认情况,将Cookie保存在浏览器缓存中,浏览器关闭,Cookie销毁。

6.常用方法:

String name = cookie.getName();//获取Cookie的名称String value = cookie.getValue();//获取Cookie的值cookie.setValue(newValue);//修改Cookie的值

7.主要应用:

Cookie主要用于保存浏览器关闭以后需要保留的会话信息,如登陆信息,实现免登陆功能。

七 Session

1.HTTP协议的无状态特性

在HTTP协议中,浏览器向服务器发送请求,服务器响应完毕后,连接结束,服务器端没有保存本次请求的任何信息,这就是HTTP协议的无状态特性。如果需要保存会话信息,就必须提供一种解决方案,而Session就是这个解决方案。

2.什么是Session?

Session是用来在服务器端保存会话信息的对象,比如保存用户在网站上的足迹等。

3.什么是同一Session?

在浏览器开启Cookie的情况下,从浏览器第一个访问网站到浏览器关闭的时间内浏览器与服务器所有的互动都是在同一个会话中。如果浏览器关闭了Cookie,那么浏览器每向服务器发送一次请求,都开启一个新的会话,即服务器端都会新建一个Session对象。

4.Session的工作原理

第一次访问时,服务器会自动创建一个Session对象,并为Session对象分配一个唯一的32位的id,同时生成一个Cookie对象,name为JSESSIONID,value为Session的id。在Cookie的有效期内,再次访问服务器时,根据value值获取对应的Session对象,这样就保证了在同一次会话中存在的始终是同一个Session对象。

5.Session的生命周期

Session对象在浏览器第一次访问服务器时创建,如果浏览器长时间不向服务器发送请求,在指定的时长之后,服务器会销毁Session对象。
    这里所说的时长不是从Session创建到销毁的时间长度,而是浏览器长时间发送请求,服务器保存Session对象的最大时间长度,通过以下方法设置,以秒为单位:

session.setMaxInactiveInterval(int interval);

6.Session的销毁

通过以下方法,浏览器可以主动销毁Session对象:

session.invalidate();

7.主要方法:

Session主要用于在同一会话中共享数据,所以对Session的主要操作是操作作用域中的属性:

session.setAttribute(name,value);//向作用域中添加属性session.getAttribute(name);//获取作用域中的属性session.removeAttribute(name);//从作用域中删除属性

八 请求转发与重定向

1.什么是请求转发?

服务器接收到请求以后,首先对请求进行预处理,然后将请求转发给其他的资源继续处理,这种转发叫做请求转发。

2.什么是重定向?

服务器调用特定的方法向浏览器发送一个资源路径,浏览器访问该路径,这一过程叫做重定向。

3.请求转发与重定向的区别

  • 请求转发是服务器调用不同的资源处理同一请求,始终是同一请求。

  • 重定向使得浏览器再次向服务器发送请求,前后是两个不同的请求。

九 异步机制

1.什么是异步机制?

为耗时的任务分配一个线程,主线程继续执行后面的代码,执行完毕,将主线程归还线程池,以便执行其他的请求。

2.异步机制产生的原因

Servlet是单例多线程的,允许并发访问的线程数目有限,为此Servlet建立了一个线程池,请求必须从线程池中获取了线程才能访问Servlet。若一个请求长时间占有线程,可能导致后面的请求长时间等待,降低了程序的吞吐能力。如果一个线程从Servlet线程池中获取了线程以后,另外开启一个线程处理耗时的任务,及时将主线程归还线程池,就解决这个问题。

3.异步机制的作用

异步机制的作用主要不是为了提高单次执行速度,而是提高吞吐量,即同一时间段内允许更多的请求访问Servlet。为了提高访问的线程数目,降低每次访问占有Servlet线程的时间,将耗时的任何交个另外一个线程处理,将主线程及时归还线程池。

4.异步机制的基本原理

Servlet接收到请求以后,对请求进行初步处理,然后开启一个异步线程处理具体的业务,Servlet线程继续执行后面的代码,执行完毕后,将Servlet线程归还线程池,以便其他请求使用。等待异步线程执行完毕后一起响应,异步线程执行完毕主要有两个标志:

  1. 在异步线程内部调用complete方法。

  2. 超时时间结束。

超时时间不并代表异步线程的生命时长,而是最大生命时长。如果在超时时长内,异步线程调用了complete方法,异步线程提前结束。
    异步线程默认的超时时长是10s(Servlet不同版本不同),当主线程执行完毕,同时超时时长结束或者异步线程提前结束,服务器开始向浏览器发送响应,销毁request、response对象,关闭输出流,如果异步线程未执行完毕,那么异步线程中已执行的响应会响应到浏览器,未执行的响应不会响应到浏览器。

  5.响应时机

   分配给异步线程的时间不是无限的,因此存在一个响应时机的问题。
    在主线程执行完毕并且异步线程超时时长用完或者提前结束时响应。

  6.异步处理的实现

AsyncContext ac=request.startAsync();
ac.setTimeout(int mills);
ac.start(Runnable run);//将异步线程管理对象ac作为参数传入异步线程中,通过该参数可以获取request\response

7.异步机制的使用

由于异步机制的设计目的是为了使请求尽快归还Servlet线程,提高程序的吞吐量,并未显著提高响应速度。异步机制通常不直接用作向浏览器输出响应内容,如在异步线程内部使用out.write直接向浏览器输出,而是用来处理耗时的任务,将处理结果存放到session/application等作用域中。

8.还可以使用AsyncContext对象为异步线程添加监听器,监听异步线程的执行过程。

十 web.xml

1.配置Servlet、Filter、Listener、contextParams等构成应用程序的重要信息。

2.配置欢迎页面,也是网站的首页,可以由多个文件构成,优先采用上面的文件:

<welcome-file-list>   <welcome-file>index.html</welcome-file>   <welcome-file>default.html</welcome-file></welcome-file-list>

注:在配置文件中书写路径时,只有欢迎列表中的路径不需要在前面加“/”,其他地方的路径都需要在前面加“/”,因为欢迎页面只能放在WebContent根路径下,不能放在WebContent根路径下的文件夹内,其路径相对固定,因此可以简写。

3.配置错误页面:

⑴方式一,根据错误代码配置页面,出现指定的错误代码时显示指定的页面:

<error-page>  <error-code>404</error-code>  <location>/xxxx</location>//可以放在WebContent目录下任意位置</error-page>

⑵方式一,根据异常类型配置页面,出现指定的异常时显示指定的页面:

<error-page> <exception-type>java.lang.NullException</exception>//异常类必须写完整的类名     <location>/xxxx</location></error-page>

4.配置ServletContext的初始化参数:

<context-param><param-name>paramName</param-name><param-value>paramValue</param-value></context-param>

十一 注解式开发

Servlet3.0新增注解式开发,注解式开发就是将在编写在配置文件web.xml中的信息转移到类文件上。

注解方式:
    在类名上添加注解:

@WebServlet(urlPatterns={"",""},loadOnStartup=1,initParams={@WebInitParam(name="",value="")},asyncSupported=true)

两种注册方式同时存在,如果映射路径不相同,相当于存在一个集中了所用路径的Servlet,如果存在相同路径,服务器无法启动。

十二 文件上传

1.Servlet3.0提供一个Part类型,该类封装了上传文件信息。

2.文件名存储在一个名为Content-Disposition的请求头中。

3.文件上传的具体实现:

Part part=request.getPart(文件字段名);//获取文件封装对象String fileName=part.getHeader("Content-Dispostion");//获取文件名part.write("parentPath/"+fileName);//将文件保存到指定路径,只能使用绝路径

十三 文件下载

1.Servlet提供了ServletOutputStream用作文件下载的输出流。

2.文件下载时必须设置浏览器以附件的形式处理从服务器获取的数据:

response.setHeader("Content-disposition","attachment;filename=xxxx");

如果请求头中设置的文件名含有中文必须转化为ISO-8859-1的编码方式。

3.从服务器获取输入流,利用ServletOutputStream输出流将文件写到用户指定路径:

InputStream is = getServletContext().getResourceAsStream("/Files/upload.txt");
ServletOutputStream os = response.getOutputStream();

With the input stream and output stream, the subsequent operation is to write the contents of the input stream to the output stream, which is a common IO operation.

Fourteen Thread Safety Issues

1. Causes of Servlet thread safety issues

Servlet runs in a multi-threaded environment in the form of a singleton, in which instance variables are stored in objects in the heap, and the heap is shared by multiple threads, so instance variables have thread safety issues, and static Variables are stored in the method area. The method area is also shared by multiple threads. Static variables also have thread safety issues, while local variables are stored in the stack. The data in the stack is shared internally and between stacks. It is not shared, that is, one thread has one stack, so local variables are thread-safe.

2. Solution to thread safety problem:

  • Convert global variables into local variables.

  • ##Add the code that modifies global variables to the synchronized method or synchronized block.

  • # Store global variables in ThrealLocal, allocate a copy of the variable to each thread, and each thread operates independently of each other.

Fifteen free login

1. According to the degree of disclosure and protection, the resources on the website are divided into open There are two types of resources and permission resources:

  • Open resources: resources that are open to all users and can be accessed without permission.

  • # Permission resources: resources that save user personal information and can only be accessed after identity verification.

2. The meaning of no login required

After logging in to the website, you will not need to use the same browser to access the website next time. Need to log in again.

3. Principle of login-free implementation

Save login information (user name, password) in Cookie, and save Cookie locally , the browser automatically submits cookies when accessing the website. After passing the Filter or Interceptor verification, you can access directly without logging in.

4. Conditions for no login required

Same browser: No login required to obtain Cookie object verification information locally.

Sixteen Servlet component pluggability

Servlet3.0 components are checkable, which means that Servlet, Filter, and Listener can Insert into the project as a shelf package.

Shelf package creation:

  • Create the project Web Fragment Project.

  • Package jar File.

  • #Put it in the lib directory and use it as a rack package.

Usage:

You can encapsulate some commonly used Servlet components into rack packages and place them directly in the lib directory Use, for example, Filter to solve Chinese garbled characters in POST requests.

Seventeen Dynamic Registration

1. What is dynamic registration?

Register Servlet, Filter, and Listener when the Web is running.

2. Dynamic registration timing

For security reasons, it can only be registered when the web server is started, that is, through the ServletContextListener listener.

The above is the detailed content of Servlet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:JAVA learningNext article:JAVA learning