In servlet 3.0 & tomcat 8 , we can get servlet mapping by the servlet name as following:
request.getServletContext().getServletRegistration(servletName).getMappings()
But in tomcat6, getServletRegistration is not exist so how to get the servlet's url mapping by the servlet name?
Since no one reply so I answer my question. I find a way to do that:
Since tomcat6 isn't support dynamic add servlet and annotation for endpoint, so I find a workaround method that direct read the servlet information form web.xml in the listener:
public class SomeListener implements ServletContextListener {
public static ServletContext context;
@Override
public void contextInitialized(ServletContextEvent sce) {
context = sce.getServletContext();
Map<String, String> valuesMap = new HashMap<String , String>();
try {
String fileName = context.getRealPath("/")+"/WEB-INF/web.xml";
FileInputStream fileInputStream = new FileInputStream(fileName);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.parse(fileInputStream);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
NodeList nodeList = (NodeList)xpath.compile("/web-app/servlet-mapping").evaluate(document, XPathConstants.NODESET);
for (int index = 0; index < nodeList.getLength(); index++) {
Node node = nodeList.item(index);
if( node instanceof Element) {
Element docElement = (Element) node;
Node cell = docElement.getElementsByTagName("servlet-name").item(0);
Node cell2 = docElement.getElementsByTagName("url-pattern").item(0);
if ( cell != null && cell2 != null ){
valuesMap.put(cell.getTextContent() , cell2.getTextContent());
}
}
}
context.setAttribute("servletMapping" , valuesMap );
System.out.println("init the servlet map." );
}catch (Exception exception){
exception.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
context = null;
}
}
And just get the mapping form context:
public static String getMapping( HttpServletRequest request , String servletName){
return ((Map<String, String>)request.getSession().getServletContext().getAttribute("servletMapping")).get(servletName);
}