jsp页面打jar包及其引用

来源:互联网 发布:matlab画出网络拓扑图 编辑:程序博客网 时间:2024/05/18 01:26

1、前言

项目开发中,需要把一些公共页面抽取到公用的项目中,打成jar包全局使用,便于修改和维护。最常见的就是会把公用的方法或者实体类打成jar包,这种很好用,直接导入依赖,导包就完事了。但是页面的打包笔者开发的时候,搞了好久,终于搞定。记录一下,方便日后使用。

2、页面的打包

  • 正确的打包方式,开发者可以像页面在项目中一样的方式去引用(js、css等同理)。

  • jar工程只用两个主要的文件夹src/main/java和src/main/resources,前者只要用来存放java代码,后者存放页面和配置文件。在maven打jar包的时候,会生成这样的结构,如图:

  • 注意,因为是jar项目,所有不会打包webapp下的文件。

3、jsp页面的打包及使用

  • 在Servlet3.0协议规范中指出:${jar}/META-INF/resources/被视为根目录。那么将jsp等静态资源打入META-INF/resources/目录下就与实际项目没有区别了。

    所以我们只需要在src/main/resources的文件夹下创建META-INF/resources/目录,然后将引用的jsp文件放在该目录下,即可正常引用。

  • 官方文档摘录:

    The getResource and getResourceAsStream methods take a String with a leading “/” as an argument that gives the path of the resource relative to the root of the context or relative to the META-INF/resources directory of a JAR file inside the web application’s WEB-INF/lib directory.

    These methods will first search the root of the web application context for the requested resource before looking at any of the JAR files in the WEB-INF/lib directory.

    The order in which the JAR files in the WEB-INF/lib directory are scanned is undefined.

    This hierarchy of documents may exist in the server’s file system, in a Web application archive file, on a remote server, or at some other location.

4、JSP打包demo

  • jar工程结构:
    这里写图片描述
    这样只要引入该jar就可以正常引入jsp页面了。

  • 页面引用:

<jsp:include page="/jsp/authentication/header.jsp"></jsp:include>