Web fragments

We can even do the same thing for external web components. The included web component inside a web application is called web fragment. To declare a web fragment, we need to put the web-fragment.xml descriptor file in an external JAR archive. Here's a sample that declares a filter:

<web-fragment version="3.1" 
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<filter>
<filter-name>LoggingFilter</filter-name>
<filter-class>it.vige.webprogramming.servletjsp.filters.LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilter</filter-name>
<url-pattern>/logging/*</url-pattern>
</filter-mapping>
</web-fragment>

This is the JAR file structure of the web fragment:



Classes must be included in the same JAR file. Here's a sample of LoggingFilter declared in the web fragment:

@WebFilter(filterName = "LoggingFilter", urlPatterns = { "/logging/*" })
public class LoggingFilter implements Filter {
...
protected void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (debug) {
log("LoggingFilter:DoBeforeProcessing");
}
}
...
}

Once we put the JAR in the WEB-INF/lib folder of the web application, we can call a servlet running in the logging context path:

@WebServlet(urlPatterns = "/logging/WebFragmentServlet")
public class WebFragmentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<h1>Web Fragment with output from Servlet Filter</h1>");
out.println("<br><br>Check server log for output from LoggingFilter");
}
...
}

As a result, we will see the following row generated by the filter of the web fragment in the log file of WildFly:


23:42:07,520 INFO [io.undertow.servlet] (default task-20) LoggingFilter:DoBeforeProcessing
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.72