Search code examples
javaservletsweb.xmlurl-pattern

url-pattern in web.xml not recognising multiple url


I have web.xml like this :

  <servlet>
    <servlet-name>MyDisplayCourse</servlet-name>
    <servlet-class>edu.itn.controller.MyDisplayCourse</servlet-class>
</servlet>

and servlet-mapping for the servlet is:

 <servlet-mapping>
    <servlet-name>MyDisplayCourse</servlet-name>
     <url-pattern>/admin/displaystudent</url-pattern>    
    <url-pattern>/displaystudent</url-pattern>    
 </servlet-mapping>

When i use :

 <url-pattern>/displaystudent</url-pattern>   

It finds the servlet MyDisplayCourse, but when i use append /admin/

 <url-pattern>/admin/displaystudent</url-pattern> 

This shows 404 error code in my web app. Can someone help me why doesn't support url like /admin/displaystudent but supports only single url like /displaystudent only.


Solution

  • There is no issue with url-pattern

    the issue is with your code in DisplayStudent.java

    replace

    RequestDispatcher rd=request.getRequestDispatcher("StudentTable.jsp");

    with

    RequestDispatcher rd=request.getRequestDispatcher("/StudentTable.jsp");

    ServletRequestSpec

    If the path begins with a "/" it is interpreted as relative to the current context root

    otherwise it will concatinate with relative path in your case '/admin/StudentTable.jsp'

    following code is implementation of getRequestDispatcher

    @Override
    public RequestDispatcher getRequestDispatcher(final String path) {
    String realPath;
     if (path.startsWith("/")) {
        realPath = path;
     } else {
        String current = exchange.getRelativePath();
        int lastSlash = current.lastIndexOf("/");
        if (lastSlash != -1) {
            current = current.substring(0, lastSlash + 1);
        }
        realPath = CanonicalPathUtils.canonicalize(current + path);
     }
     return new RequestDispatcherImpl(realPath, servletContext);
    }