Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

servlets - Splitting up shared code and web.xml from WAR project to common JAR project

I have different webapps that share a large portion of the web.xml configuration. For example, the way some servlets are mapped is identical for all apps, but some webapps have custom servlets, or an additional filter, or shared managed beans.

Each webapp is a different project in my IDE. I would like to refactor the common part of my web.xml to a "common" project, and let all the application-specific web.xml's extend the "common" web.xml. Is there any possibility to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you can. Assuming Eclipse (your question history confirms that you're using it), just create a "Web Fragment Project":

enter image description here

And associate it with the main project in the wizard:

enter image description here

You can if necessary (re)configure it in "Deployment Assembly" property of the main web project (or any other way of configuring the build in such way that it ultimately ends up as JAR in /WEB-INF/lib of main web project).

enter image description here

It's basically a Java project with the following folder structure:

CommonWebProject
 |-- com.example... (you can put e.g. @WebServlet classes here)
 |
 |-- META-INF
 |    |-- resources (you can put shared web resources here)
 |    |    |-- common.css
 |    |    |-- common.js
 |    |    |-- template.jsp
 |    |    :
 |    |
 |    |-- beans.xml
 |    |-- web-fragment.xml
 |    `-- MANIFEST.MF
 :

Any content in /META-INF/resources folder is resolved the same way as webcontent of the WAR (my Eclipse Luna SR1 didn't precreate the /resources folder, so you'd need to manually create it). And, importantingly, any resources (including classes!) with the same name already in the WAR will have loading precedence over those in JAR, so you could if necessary "override" a common JAR resource from WAR on that way.

Note that the web-fragment.xml file must be named exactly like that and thus not web.xml. The IDE should just autogenerate one for you, but for sake of completeness, a Servlet 3.0 compatible one look like this:

<?xml version="1.0" encoding="utf-8"?>
<web-fragment
    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-fragment_3_0.xsd"
    version="3.0"
>

    <!-- Put shared web.xml config here. -->

</web-fragment>

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...