Reputation: 15
this is my path
<welcome-file>home</welcome-file>
and my servlet ,I declare urlpattern belows
@WebServlet(urlPatterns="/home")
and forward to file homeview.jsp
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/SimpleWebApp/WebContent/WEB-INF/views/homeview.jsp");
dispatcher.forward(request, response);
but when i run my web app it error with htttp status 404 anyboby,help me fix it?Thank alot
Upvotes: 1
Views: 104
Reputation: 291
A welcome file can only be a static file, so for example a jsp or html file, it cannot specify a servlet.
If you want a servlet to act as a welcome page you should set its mapping to /* which makes it a default servlet. So in your annotation:
@WebServlet(urlPatterns="/*")
This way the servlet will be called whenever a request is received which does not map to any other resources.
Also you need to fix your forward request to specify the url relative to the content root of the app as shown in the other answer.
For reference this is how mapping works according to the servlet spec (this text taken from Section 12.1 of the Servlet 3.0 specification) :
The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a "default" servlet is defined for the application, it will be used. Many containers provide an implicit default servlet for serving content.
Upvotes: 0
Reputation: 2675
Your code is working correctly. But,
Like the following in the project structure, you can access it this way.
HomeController (yourServlet)
request.getRequestDispatcher("/WEB-INF/views/homeview.jsp").forward(request, response);
Structure
WebContent
|
|__static
|
|__WEB-INF
|__lib
|__views/homeview.jsp
|__web.xml
Upvotes: 2