I have manually configured web.xml
for my application. Now, I'm facing issues while running my application. I'm trying to access my servlet
from my jsp
page. But, it is throwing error as page not found
.
The servlets are placed under below folder location
<application folder>/WEB-INF/classes/<package>
So, what should be the entries for servlets in url-pattern
and servlet-mapping
. So that, servlet
can be accessible through URL.
Servlets and URL Paths xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and call the class method that corresponds to the request method (e.g. the doGet() method for HTTP GET requests).
The url-pattern element of a servlet-mapping or a filter-mapping associates a filter or servlet with a set of URLs. When a request arrives, the container uses a simple procedure for matching the URL in the request with a url-pattern in the web. xml file.
Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.
url-pattern
is used in web.xml
to map your servlet
to specific URL. Please see below xml code, similar code you may find in your web.xml
configuration file.
<servlet> <servlet-name>AddPhotoServlet</servlet-name> //servlet name <servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class </servlet> <servlet-mapping> <servlet-name>AddPhotoServlet</servlet-name> //servlet name <url-pattern>/AddPhotoServlet</url-pattern> //how it should appear </servlet-mapping>
If you change url-pattern
of AddPhotoServlet
from /AddPhotoServlet
to /MyUrl
. Then, AddPhotoServlet
servlet can be accessible by using /MyUrl
. Good for the security reason, where you want to hide your actual page URL.
Java Servlet url-pattern
Specification:
- A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
- A string beginning with a '*.' prefix is used as an extension mapping.
- A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
- All other strings are used for exact matches only.
Reference : Java Servlet Specification
You may also read this Basics of Java Servlet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With