Jonathan Laliberte
Jonathan Laliberte

Reputation: 2725

How to check if requested URL is a servlet (in a filter)?

I have a filter that maps onto all requests:

@WebFilter({ "/*" })

I use this filter to do url mapping so that i can have vanity urls for my jsps and to handle 404s, however it also means i have to manually add the servlets to process the request chain normally:

String requri = ((HttpServletRequest) request).getRequestURI(); //get requested url
String page = "";

if(requri.equals("/contact/") || requri.equals("/contact"))
   page = "contact.jsp";

else if(requri.equals("/about/") || requri.equals("/about"))
   page = "about.jsp";

else if(requri.equals("/SomeServlet"))
   chain.doFilter(request, response); //if requested url is a servlet, then carry on normally

//send requested url to servlet which will then forward user to the appropriate page
request.getRequestDispatcher("/GetPage?page="+page).forward(request, response);
return;

It all works great.

But is there a way to get a list of the url mappings for all the servlets? So that i don't have to manually list each url mapping for the servlets.. i.e:

else if(requri.equals("/SomeServlet") || requri.equals("/AnotherServlet") || requri.equals("/SomeOtherServlet"))
   chain.doFilter(request, response); //if requested url is a servlet, then carry on normally

The ideal:

else if(isAServlet(requri))
   chain.doFilter(request, response); //if requested url is a servlet, then carry on normally

Upvotes: 0

Views: 1075

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

If you are in JEE >= JEE 7 there is ServletContext.getServletRegistrations(). It returns a map from servlet names to ServletRegistration objects. These have a getMappings() method that gets you the URL mappings for that servlet. You will probably have to process these a bit, e.g. apply the servlet URL mapping rules manually, to see which servlet, if any, would get called.

Upvotes: 1

Related Questions