浅谈JSP是如何编译成servlet并提供服务的

 更新时间:2021年07月07日 10:27:54   作者:黄智霖-blog  
JSP是Servlet的一种特殊形式,JSP页面最终是编译为Servlet执行的,那么本文主要介绍了JSP是如何编译成servlet并提供服务的,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

概述

服务端对外提供JSP请求服务的是JspServlet,继承自HttpServlet。核心服务入口在service方法,大体流程如下:

  • 首先获取请求的jspUri,如果客户端发起请求:https://xxx.xx.com/jsp/test.jsp,那么获取到的jspUri为:/jsp/test.jsp
  • 然后查看缓存(Map结构)中是否包含该jspUri的JspServletWrapper,如果没有就需要创建一个JspServletWrapper并且缓存起来,并调用JspServletWrapper的service方法
  • 如果为development模式,或者首次请求,那么就需要执行JspCompilationContext.compile() 方法
  • 在JspCompilationContext.compile方法中,会根据jsp文件的lastModified判断文件是否已经被更新(out dated),如果被更新过了,就需要删除之前生成的相关文件,然后将jspLoader置空(后面需要加载的时候如果jspLoader为空,就会创建一个新的jspLoader),调用Compiler.compile方法生成servlet,设置reload为true(默认为true),后面会根据reload参数判断是否需要重新加载该servlet
  • 调用JspServletWrapper.getServlet方法获取最终提供服务的servlet,这个过程会根据reload参数看是否需要重载servlet,如果需要重载,那么就会获取jspLoader实例化一个新的servlet(如果前面发现jsp文件过期,那么此时获取的jspLoader为空,则会创建一个新的jspLoader),并且设置reload为false
  • 调用servlet的service方法提供服务,如果servlet实现了SingleThreadModel接口,那么会用synchronized做同步控制

源码分析

首先看JspServlet的核心逻辑,主要是获取jspUri和获取JspServletWrapper,分别是入口service方法和serviceJspFile方法,代码如下(部分):

/**
 * 获取jspUri,然后调用serviceJspFile方法
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jspUri = this.jspFile;
        String pathInfo;
        if (jspUri == null) {
            pathInfo = (String)request.getAttribute(Constants.JSP_FILE);
            if (pathInfo != null) {
                jspUri = pathInfo;
                request.removeAttribute(Constants.JSP_FILE);
            }
        }
 
        if (jspUri == null) {
            jspUri = (String)request.getAttribute("javax.servlet.include.servlet_path");
            if (jspUri != null) {
                pathInfo = (String)request.getAttribute("javax.servlet.include.path_info");
                if (pathInfo != null) {
                    jspUri = jspUri + pathInfo;
                }
            } else {
                jspUri = request.getServletPath();
                pathInfo = request.getPathInfo();
                if (pathInfo != null) {
                    jspUri = jspUri + pathInfo;
                }
            }
        }
 
 
        boolean precompile = this.preCompile(request);
        this.serviceJspFile(request, response, jspUri, precompile);
    }
 
 
/**
 * 主要获取JspServletWrapper,然后调用JspServletWrapper.service方法
 */
private void serviceJspFile(HttpServletRequest request, HttpServletResponse response, String jspUri, boolean precompile) throws ServletException, IOException {
        JspServletWrapper wrapper = this.rctxt.getWrapper(jspUri);
        if (wrapper == null) {
            synchronized(this) {
                wrapper = this.rctxt.getWrapper(jspUri);
                if (wrapper == null) {
                    if (null == this.context.getResource(jspUri)) {
                        this.handleMissingResource(request, response, jspUri);
                        return;
                    }
 
                    wrapper = new JspServletWrapper(this.config, this.options, jspUri, this.rctxt);
                    this.rctxt.addWrapper(jspUri, wrapper);
                }
            }
        }
 
        try {
            //核心服务方法
            wrapper.service(request, response, precompile);
        } catch (FileNotFoundException var8) {
            this.handleMissingResource(request, response, jspUri);
        }
 
    }

然后进入JspServletWrapper.service方法(部分代码):

//注意这个reload是volatile修饰的
private volatile boolean reload = true;
 
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException {
        Servlet servlet;
        try {
            if (this.ctxt.isRemoved()) {
                throw new FileNotFoundException(this.jspUri);
            }
            //判断development模式和firstTime(首次请求)
            if (!this.options.getDevelopment() && !this.firstTime) {
                if (this.compileException != null) {
                    throw this.compileException;
                }
            } else {
                synchronized (this) {
                    this.firstTime = false;
                    //调用JspCompilationContext.compile方法
                    this.ctxt.compile();
                }
            }
            //获取最终提供服务的servlet
            servlet = this.getServlet();
            if (precompile) {
                return;
            }
        }
        try {
            //根据是否实现SingleThreadModel决定是否需要做同步控制
            if (servlet instanceof SingleThreadModel) {
                synchronized (this) {
                    servlet.service(request, response);
                }
            } else {
                servlet.service(request, response);
            }
        }
    }

这里主要看JspCompilationContext.complie方法:

public void compile() throws JasperException, FileNotFoundException {
        this.createCompiler();
        if (this.jspCompiler.isOutDated()) {
            if (this.isRemoved()) {
                throw new FileNotFoundException(this.jspUri);
            }
            try {
                //清楚文件数据
                this.jspCompiler.removeGeneratedFiles();
                //置空jspLoader,现在置null,后面就会创建一个新的JspLoader
                this.jspLoader = null;
                //根据jsp生成servlet的逻辑,实现主要有AntCompiler和JDTCompiler,默认JDTCompiler
                this.jspCompiler.compile();
                //设置reload为true,后面根据reload参数判断是否需要重新加载
                this.jsw.setReload(true);
                this.jsw.setCompilationException((JasperException) null);
            }
        }
    }

要注意对于isOutDated方法的判断,并不是简单地每次请求都检查jsp文件是否更新,而是有一个间隔时间,如果此次检查更新的时间在上一次检查更新+间隔时间之内,也就是没有超过间隔时间,那么就不会去检查jsp文件的更新。这就是我们说的jsp热更新延时生效,isOutDated是Compiler的方法,如下(部分代码):

    public boolean isOutDated(boolean checkClass) {
        if (this.jsw != null && this.ctxt.getOptions().getModificationTestInterval() > 0) {
            //getModificationTestInterval就是检查最短间隔时间,单位为秒
            if (this.jsw.getLastModificationTest() + (long)(this.ctxt.getOptions().getModificationTestInterval() * 1000) > System.currentTimeMillis()) {
                return false;
            }
 
            this.jsw.setLastModificationTest(System.currentTimeMillis());
        }
 
        Long jspRealLastModified = this.ctxt.getLastModified(this.ctxt.getJspFile());
        if (jspRealLastModified < 0L) {
            return true;
        } else {
            long targetLastModified = 0L;
            File targetFile;
            if (checkClass) {
                targetFile = new File(this.ctxt.getClassFileName());
            } else {
                targetFile = new File(this.ctxt.getServletJavaFileName());
            }
 
            if (!targetFile.exists()) {
                return true;
            } else {
                targetLastModified = targetFile.lastModified();
                if (checkClass && this.jsw != null) {
                    this.jsw.setServletClassLastModifiedTime(targetLastModified);
                }
 
                if (targetLastModified != jspRealLastModified) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Compiler: outdated: " + targetFile + " " + targetLastModified);
                    }
 
                    return true;
                } else if (this.jsw == null) {
                    return false;
                } 
            }
        }

另外,这里还涉及到JSP的编译工作,编译工作主要由org.apache.jasper.compiler.Compiler编译器负责,Compiler是一个抽象类,apache-jsp中提供了两种实现:AntCompilerJDTCompiler,默认使用的编译器为JDTCompiler。

最后回到JspServletWrapper.getServlet方法:

private volatile boolean reload = true;
public Servlet getServlet() throws ServletException {
        //reload是被volatile修饰的一个boolean变量
        //这里进行双重检测
        if (this.reload) {
            synchronized (this) {
                if (this.reload) {
                    //需要重载
                    this.destroy();
                    Servlet servlet;
                    try {
                        InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(this.config);
                        //创建一个新的serlvet实例对象,注意这里的getJspLoader方法
                        servlet = (Servlet) instanceManager.newInstance(this.ctxt.getFQCN(), this.ctxt.getJspLoader());
                    } catch (Exception var6) {
                        Throwable t = ExceptionUtils.unwrapInvocationTargetException(var6);
                        ExceptionUtils.handleThrowable(t);
                        throw new JasperException(t);
                    }
 
                    servlet.init(this.config);
                    if (!this.firstTime) {
                        this.ctxt.getRuntimeContext().incrementJspReloadCount();
                    }
                    this.theServlet = servlet;
                    this.reload = false;
                }
            }
        }
        return this.theServlet;
    }

可以看到,方法中使用了双重检测机制判断是否需要重载,reload参数由volatile修饰保证可见性。在创建新的servlet实例的时候,classLoader是通过JspCompilationContext.getJspLoader方法获取的,看看这个方法的逻辑:

public ClassLoader getJspLoader() {
        if (this.jspLoader == null) {
            this.jspLoader = new JasperLoader(new URL[]{this.baseUrl}, this.getClassLoader(), this.rctxt.getPermissionCollection());
        }
 
        return this.jspLoader;
    }

在前面JspCompilationContext.complie的逻辑中,如果检测到jsp文件被更新过(过期),那么jspLoader会被设置为null,此时就会创建一个新的jspLoader(JasperLoader),然后使用新的loader加载新的servlet,以完成jsp的热更新,老的classloader在之后会被GC直接回收。

到此这篇关于浅谈JSP是如何编译成servlet并提供服务的的文章就介绍到这了,更多相关JSP编译成servlet内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot中的@CacheEvict 注解的实现

    SpringBoot中的@CacheEvict 注解的实现

    本文主要介绍了SpringBoot中的@CacheEvict注解的实现,@CacheEvict 注解用于清空缓存,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2024-03-03
  • 使用EasyExcel实现简单的Excel表格解析操作

    使用EasyExcel实现简单的Excel表格解析操作

    这篇文章主要介绍了如何使用EasyExcel完成简单的表格解析操作,同时实现了大量数据情况下数据的分次批量入库,并记录每条数据入库的状态,感兴趣的可以了解下
    2025-03-03
  • Spring中HandlerAdapter接口源码解析

    Spring中HandlerAdapter接口源码解析

    这篇文章主要介绍了Spring中HandlerAdapter接口源码解析,HandlerAdapter是一个适配器接口类,适配器模式是指两个不兼容接口之间的桥梁,要想让一个接口使用另外一个接口的实现中间可以加一层适配器类,需要的朋友可以参考下
    2023-11-11
  • 如何实现Java监听器详解

    如何实现Java监听器详解

    今天带大家了解Java监听器是如何实现的及实现原理是什么,文中有非常详细的说明,对正在学习的小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • SpringBoot对Filter过滤器中的异常进行全局处理方案详解

    SpringBoot对Filter过滤器中的异常进行全局处理方案详解

    这篇文章主要介绍了SpringBoot对Filter过滤器中的异常进行全局处理,在SpringBoot中我们通过 @ControllerAdvice 注解和 @ExceptionHandler注解注册了全局异常处理器,需要的朋友可以参考下
    2023-09-09
  • Java详解表格的创建与使用流程

    Java详解表格的创建与使用流程

    这篇文章主要介绍了怎么用Java来创建和使用表格,表格是我们经常要用的工具,但是你有想过自己怎么去实现它吗,感兴趣的朋友跟随文章往下看看吧
    2022-04-04
  • java实现emqx设备上下线监听详解

    java实现emqx设备上下线监听详解

    这篇文章主要为大家介绍了java实现emqx设备上下线监听详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • 详解SpringBoot是如何保证接口安全的

    详解SpringBoot是如何保证接口安全的

    对于互联网来说,只要你系统的接口会暴露在外网,就避免不了接口安全问题。 如果你的接口在外网裸奔,只要让黑客知道接口的地址和参数就可以调用,那简直就是灾难。这篇文章主要介绍了SpringBoot保证接口安全的方法,需要的可以参考一下
    2023-02-02
  • 在Filter中不能注入bean的问题及解决

    在Filter中不能注入bean的问题及解决

    这篇文章主要介绍了在Filter中不能注入bean的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • Maven的配置文件pom.xml详解(含常用plugin)

    Maven的配置文件pom.xml详解(含常用plugin)

    pom.xml是Maven项目的核心配置文件,它是 项目对象模型 - Project Object Model(POM)的缩写,本文我们将全面解析pom.xml,了解其结构和属性,以及如何使用它来管理项目,感兴趣的朋友跟随小编一起看看吧
    2024-08-08

最新评论