SpringMVC提高篇(四):从Servlet到DispatcherServlet源码分析

来源:互联网 发布:java ireport案例 编辑:程序博客网 时间:2024/06/06 20:55

1.从Servlet到HttpServlet

Servlet的定义和源码;

import java.io.IOException;/** * 定义了所有servlet必须实现的方法 * 一个Servlet就是一个运行在Web服务上的小程序。 * Servlet负责接收和响应来自Web客户端通过HTTP协议发送的请求, * 对于Servlet的接口有一个一般的实现可以直接继承 <code>javax.servlet.GenericServlet</code>           如果是HTTP的 servlet可以直接继承<code>javax.servlet.http.HttpServlet</code>. * 这个接口定义了初始化一个Servlet的方法来服务客户端请求,同时也定义了从服务中移除一个Servlet。 * 这就是Servlet的生命周期: * 1.通过init方法创建. * 2.所有的请求都是被service方法处理。 * 3.Servlet调用destroy方法后销毁, 然后完成垃圾回收. * 除了Servlet的生命周期方法,接口中还提供了 <code>getServletConfig</code> 方法,该方法可以获取任何的启动时设置的参数信息。 *<code>getServletInfo</code>方法允许Servlet返回一些自身的基础信息如作者,版本号,版权等。 */public interface Servlet {    /**     *由servlet容器调用以向servlet指示servlet正在投入使用。Servlet容器调用<code>init</code>方法整个Servlet初始化过程中只调用一次     *在Servlet接受请求之前init方法必须成功初始化完成。     */    public void init(ServletConfig config) throws ServletException;    public ServletConfig getServletConfig();    /**     *Servlet容器来调用此方法来响应请求。这个方法只在init方法成功执行之后才能被调用,应该为servlet设置响应的状态代码抛出或发送错误。     * Servlet通常在可以同时处理多个请求的多线程servlet容器中运行,开发人员必须意识到同步访问任何共享资源,如文件,网络连接以及servlet的类和实例变量。     */    public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;    public String getServletInfo();        /**     *由servlet容器调用以向servlet指示servlet正在停止服务。      *只有在servlet的<code>服务</ code>方法中的所有线程已经退出或超时时间过后,才会调用此方法。      *在servlet容器调用此方法之后,它将不会在此servlet上再次调用<code> service </ code>方法。     *此方法使servlet有机会清理正在保存的任何资源(例如,内存,文件句柄,线程),并确保任何持久状态与内存中的servlet当前状态同步。     *     */    public void destroy();}

在Servlet中引入了ServletConfig,和ServletException,ServletRequestServletResponse 。ServletException没什么好说的就是一个Exception的子类

重点看看ServletConfig源码:

import java.util.Enumeration;/** *一个Servlet配置对象,被Servlet容器用来传递Servlet初始化中的信息 */public interface ServletConfig {        /**     * 返回Servlet对象实例的名称。     * 该名称可以通过服务器管理来分配,Web应用程序部署描述符,或未注册的(因此未命名)servlet实例将是servlet的类名。     */    public String getServletName();    /**     *返回对调用者正在执行的{@link ServletContext}的引用     */    public ServletContext getServletContext();        /**                  返回一个初始化参数字符串,不存在则返回null     */    public String getInitParameter(String name);    /**     *返回Servlet初始化参数集合,不存在返回null     */    public Enumeration getInitParameterNames();}

在ServletConfig中引入了另外一个接口,也就是ServletContext。

package spring;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.Enumeration;import java.util.Set;/** * 定义servlet用于与其servlet容器进行通信的一组方法,例如获取文件的MIME类型,调度请求或写入日志文件 * <p>T每个Java虚拟机每个“Web应用程序”都有一个上下文。 (一个“web应用程序”是安装在一个下的servlet和内容的集合服务器的URL命名空间的特定子集,如<code> / catalog </ code>  并且可能通过<code> .war </ code>文件安装。)在其部署描述符中标记为“分布式”的Web应用程序的情况下,每个虚拟机将有一个上下文实例。 在这种情况下,上下文不能用作共享全局信息的位置(因为信息不是真正的全局信息)。   使用像数据库这样的外部资源。   ServletContext对象是包含在ServletConfig对象中的,其是由在servlet初始化之后由Web服务器提供的。 * the {@link ServletConfig} object, which the Web server provides the */public interface ServletContext {    /**     *返回web应用的上下文路径。     *上下文路径是用于选择请求的上下文的请求URI的部分。     * 上下文路径始终位于请求URI中。 路径以“/”字符开头,但不以“/”字符结尾。 对于默认(root)上下文中的servlet,此方法返回“”。        servlet容器可能会通过多个上下文路径匹配上下文。例如使用        {@link javax.servlet.http.HttpServletRequest#getContextPath()}                    将会返回一个实际的上下文路径     */    public String getContextPath();    /**     *返回与服务器上指定URL对应的<code> ServletContext </ code>对象                 此方法允许servlet访问服务器各个部分的上下文,并根据需要从上下文获取{@link RequestDispatcher}对象。     * 给定的路径必须以“/”开头,相对于服务器的文档根目录进行解释,并与托管在此容器上的其他Web应用程序的上下文根进行匹配。                 在安全设定的环境中,servlet容器可能会返回给定URL的<code> null </ code>。     */    public ServletContext getContext(String uripath);        /**               返回此Servlet容器支持的Java Servlet API的主要版本。 符合2.5版本的所有实现都必须使用此方法返回整数2。     */        public int getMajorVersion();    /**     * 返回此servlet容器支持的Servlet API的次要版本。 符合2.5版本的所有实现都必须使用此方法返回整数5     */    public int getMinorVersion();    /**     * 返回指定文件的MIME类型,如果未知类型则返回 <code>null</code>      * MIME类型由servlet容器的配置确定,可以在Web应用程序部署描述符中指定。     *  常见的MIME类型是<code>“text / html”</ code>和<code>“image / gif”</ code>。     */    public String getMimeType(String file);        /**            返回一个类似目录的列表,它列出了Web应用程序中资源的最长路径,其最长子路径与提供的路径参数相匹配。              指示子目录路径的路径以'/'结尾。 返回的路径都是相对于Web应用程序的根目录,并且具有前导“/”。              例如,对于包含的Web应用程序    * /welcome.html<br>    * /catalog/index.html<br>    * /catalog/products.html<br>    * /catalog/offers/books.html<br>    * /catalog/offers/music.html<br>    * /customer/login.jsp<br>    * /WEB-INF/web.xml<br>    * /WEB-INF/classes/com.acme.OrderServlet.class,<br><br>    *    * getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}<br>    * getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html", "/catalog/offers/"}.<br>    * @since Servlet 2.3    */        public Set getResourcePaths(String path);            /**                       返回映射到指定路径的资源的URL。 该路径必须以“/”开头,并被解释为相对于当前上下文根     * <p>此方法允许servlet容器使资源从任何来源可用于servlet。 资源可以位于本地或远程文件系统,数据库或<code> .war </ code>文件中。          servlet容器必须实现访问资源所必需的URL处理程序和<code> URLConnection </ code>对象.     *如果资源不存在则返回null,一些容器可能允许使用URL类的方法写入此方法返回的URL.     *     * <p>The resource content is returned directly, so be aware that      * requesting a <code>.jsp</code> page returns the JSP source code.     * Use a <code>RequestDispatcher</code> instead to include results of      * an execution.     *     * <p>This method has a different purpose than     * <code>java.lang.Class.getResource</code>,     * which looks up resources based on a class loader. This     * method does not use class loaders.     *      * @param path a <code>String</code> specifying     *the path to the resource     *     * @return the resource located at the named path,     * or <code>null</code> if there is no resource     *at that path     *     * @exception MalformedURLException if the pathname is not given in      * the correct form     *     */        public URL getResource(String path) throws MalformedURLException;            /**     * Returns the resource located at the named path as     * an <code>InputStream</code> object.     *     * <p>The data in the <code>InputStream</code> can be      * of any type or length. The path must be specified according     * to the rules given in <code>getResource</code>.     * This method returns <code>null</code> if no resource exists at     * the specified path.      *      * <p>Meta-information such as content length and content type     * that is available via <code>getResource</code>     * method is lost when using this method.     *     * <p>The servlet container must implement the URL handlers     * and <code>URLConnection</code> objects necessary to access     * the resource.     *     * <p>This method is different from      * <code>java.lang.Class.getResourceAsStream</code>,     * which uses a class loader. This method allows servlet containers      * to make a resource available     * to a servlet from any location, without using a class loader.     *      *     * @param path a <code>String</code> specifying the path     *to the resource     *     * @return the <code>InputStream</code> returned to the      *servlet, or <code>null</code> if no resource     *exists at the specified path      *     *     */    public InputStream getResourceAsStream(String path);        /**     *      * Returns a {@link RequestDispatcher} object that acts     * as a wrapper for the resource located at the given path.     * A <code>RequestDispatcher</code> object can be used to forward      * a request to the resource or to include the resource in a response.     * The resource can be dynamic or static.     *     * <p>The pathname must begin with a "/" and is interpreted as relative     * to the current context root.  Use <code>getContext</code> to obtain     * a <code>RequestDispatcher</code> for resources in foreign contexts.     * This method returns <code>null</code> if the <code>ServletContext</code>     * cannot return a <code>RequestDispatcher</code>.     *     * @param path a <code>String</code> specifying the pathname     *to the resource     *     * @return a <code>RequestDispatcher</code> object     *that acts as a wrapper for the resource     *at the specified path, or <code>null</code> if      *the <code>ServletContext</code> cannot return     *a <code>RequestDispatcher</code>     *     * @see RequestDispatcher     * @see ServletContext#getContext     *     */    public RequestDispatcher getRequestDispatcher(String path);    /**     * Returns a {@link RequestDispatcher} object that acts     * as a wrapper for the named servlet.     *     * <p>Servlets (and JSP pages also) may be given names via server      * administration or via a web application deployment descriptor.     * A servlet instance can determine its name using      * {@link ServletConfig#getServletName}.     *     * <p>This method returns <code>null</code> if the      * <code>ServletContext</code>     * cannot return a <code>RequestDispatcher</code> for any reason.     *     * @param name a <code>String</code> specifying the name     *of a servlet to wrap     *     * @return a <code>RequestDispatcher</code> object     *that acts as a wrapper for the named servlet,     *or <code>null</code> if the <code>ServletContext</code>     *cannot return a <code>RequestDispatcher</code>     *     * @see RequestDispatcher     * @see ServletContext#getContext     * @see ServletConfig#getServletName     *     */    public RequestDispatcher getNamedDispatcher(String name);                    /**     *     * @deprecatedAs of Java Servlet API 2.1, with no direct replacement.     *     * <p>This method was originally defined to retrieve a servlet     * from a <code>ServletContext</code>. In this version, this method      * always returns <code>null</code> and remains only to preserve      * binary compatibility. This method will be permanently removed      * in a future version of the Java Servlet API.     *     * <p>In lieu of this method, servlets can share information using the      * <code>ServletContext</code> class and can perform shared business logic     * by invoking methods on common non-servlet classes.     *     */    public Servlet getServlet(String name) throws ServletException;                  /**     *     * @deprecatedAs of Java Servlet API 2.0, with no replacement.     *     * <p>This method was originally defined to return an <code>Enumeration</code>     * of all the servlets known to this servlet context. In this     * version, this method always returns an empty enumeration and     * remains only to preserve binary compatibility. This method     * will be permanently removed in a future version of the Java     * Servlet API.     *     */        public Enumeration getServlets();                        /**     * @deprecatedAs of Java Servlet API 2.1, with no replacement.     *     * <p>This method was originally defined to return an      * <code>Enumeration</code>     * of all the servlet names known to this context. In this version,     * this method always returns an empty <code>Enumeration</code> and      * remains only to preserve binary compatibility. This method will      * be permanently removed in a future version of the Java Servlet API.     *     */     public Enumeration getServletNames();                    /**     *     * Writes the specified message to a servlet log file, usually     * an event log. The name and type of the servlet log file is      * specific to the servlet container.     *     *     * @param msg a <code>String</code> specifying the      *message to be written to the log file     *     */         public void log(String msg);                    /**     * @deprecatedAs of Java Servlet API 2.1, use     * {@link #log(String message, Throwable throwable)}      *instead.     *     * <p>This method was originally defined to write an      * exception's stack trace and an explanatory error message     * to the servlet log file.     *     */    public void log(Exception exception, String msg);                    /**     * Writes an explanatory message and a stack trace     * for a given <code>Throwable</code> exception     * to the servlet log file. The name and type of the servlet log      * file is specific to the servlet container, usually an event log.     *     *     * @param message a <code>String</code> that      *describes the error or exception     *     * @param throwable the <code>Throwable</code> error      *or exception     *     */        public void log(String message, Throwable throwable);                        /**     * Returns a <code>String</code> containing the real path      * for a given virtual path. For example, the path "/index.html"     * returns the absolute file path on the server's filesystem would be     * served by a request for "http://host/contextPath/index.html",     * where contextPath is the context path of this ServletContext..     *     * <p>The real path returned will be in a form     * appropriate to the computer and operating system on     * which the servlet container is running, including the     * proper path separators. This method returns <code>null</code>     * if the servlet container cannot translate the virtual path     * to a real path for any reason (such as when the content is     * being made available from a <code>.war</code> archive).     *     *     * @param path a <code>String</code> specifying a virtual path     *     *     * @return a <code>String</code> specifying the real path,     *                  or null if the translation cannot be performed     *     *     */    public String getRealPath(String path);            /**     * Returns the name and version of the servlet container on which     * the servlet is running.      *     * <p>The form of the returned string is      * <i>servername</i>/<i>versionnumber</i>.     * For example, the JavaServer Web Development Kit may return the string     * <code>JavaServer Web Dev Kit/1.0</code>.     *     * <p>The servlet container may return other optional information      * after the primary string in parentheses, for example,     * <code>JavaServer Web Dev Kit/1.0 (JDK 1.1.6; Windows NT 4.0 x86)</code>.     *     *     * @return a <code>String</code> containing at least the      *servlet container name and version number     *     */    public String getServerInfo();            /**     * Returns a <code>String</code> containing the value of the named     * context-wide initialization parameter, or <code>null</code> if the      * parameter does not exist.     *     * <p>This method can make available configuration information useful     * to an entire "web application".  For example, it can provide a      * webmaster's email address or the name of a system that holds      * critical data.     *     * @paramnamea <code>String</code> containing the name of the     *                  parameter whose value is requested     *      * @return a <code>String</code> containing at least the      *servlet container name and version number     *     * @see ServletConfig#getInitParameter     */    public String getInitParameter(String name);            /**     * Returns the names of the context's initialization parameters as an     * <code>Enumeration</code> of <code>String</code> objects, or an     * empty <code>Enumeration</code> if the context has no initialization     * parameters.     *     * @return an <code>Enumeration</code> of <code>String</code>      *                  objects containing the names of the context's     *                  initialization parameters     *     * @see ServletConfig#getInitParameter     */    public Enumeration getInitParameterNames();            /**     * Returns the servlet container attribute with the given name,      * or <code>null</code> if there is no attribute by that name.     * An attribute allows a servlet container to give the     * servlet additional information not     * already provided by this interface. See your     * server documentation for information about its attributes.     * A list of supported attributes can be retrieved using     * <code>getAttributeNames</code>.     *     * <p>The attribute is returned as a <code>java.lang.Object</code>     * or some subclass.     * Attribute names should follow the same convention as package     * names. The Java Servlet API specification reserves names     * matching <code>java.*</code>, <code>javax.*</code>,     * and <code>sun.*</code>.     *     *     * @param name a <code>String</code> specifying the name      *of the attribute     *     * @return an <code>Object</code> containing the value      *of the attribute, or <code>null</code>     *if no attribute exists matching the given     *name     *     * @see ServletContext#getAttributeNames     *     */      public Object getAttribute(String name);                /**     * Returns an <code>Enumeration</code> containing the      * attribute names available     * within this servlet context. Use the     * {@link #getAttribute} method with an attribute name     * to get the value of an attribute.     *     * @return an <code>Enumeration</code> of attribute      *names     *     * @see#getAttribute     *     */    public Enumeration getAttributeNames();                    /**     *     * Binds an object to a given attribute name in this servlet context. If     * the name specified is already used for an attribute, this     * method will replace the attribute with the new to the new attribute.     * <p>If listeners are configured on the <code>ServletContext</code> the       * container notifies them accordingly.     * <p>     * If a null value is passed, the effect is the same as calling      * <code>removeAttribute()</code>.     *      * <p>Attribute names should follow the same convention as package     * names. The Java Servlet API specification reserves names     * matching <code>java.*</code>, <code>javax.*</code>, and     * <code>sun.*</code>.     *     *     * @param name a <code>String</code> specifying the name      *of the attribute     *     * @param object an <code>Object</code> representing the     *attribute to be bound     *     *     *     */        public void setAttribute(String name, Object object);            /**     * Removes the attribute with the given name from      * the servlet context. After removal, subsequent calls to     * {@link #getAttribute} to retrieve the attribute's value     * will return <code>null</code>.     * <p>If listeners are configured on the <code>ServletContext</code> the      * container notifies them accordingly.     *     *     * @param namea <code>String</code> specifying the name      * of the attribute to be removed     *     */    public void removeAttribute(String name);        /**     * Returns the name of this web application corresponding to this ServletContext as specified in the deployment     * descriptor for this web application by the display-name element.     *     *     * @return    The name of the web application or null if no name has been declared in the deployment descriptor.     * @since Servlet 2.3     */        public String getServletContextName();}



0 0
原创粉丝点击