问题
This is a quick question but I couldn't find a quick answer. Now I have a servlet BaseServlet, when user request any of the url below:
host
host/
host/BaseServlet
It should always refer to the same servlet and redirect to the homepage.
When I set
@WebServlet({"/BaseServlet", ""})
Only
host/
host/BaseServlet
works
If I set
@WebServlet({"/BaseServlet", "", "/"})
The BaseServlet will be requested constantly in loop ...
Why?
Edit: BaseServlet does a forward to the index.html hid in WEB-INF folder and that's it.
getServletContext().getRequestDispatcher("/WEB-INF/index.html").forward(request,response);
The servlet spec says "A string containing only the / character indicates the "default" servlet of the application." So I want the BaseServlet to be my default. Why it doesn't work?
回答1:
As you state in your Q, if you want the following:
host/ host/BaseServlet
Use
@WebServlet({"/BaseServlet", ""})
If you want the following:
host
Add this to your welcome file (you can't specifiy welcome files using annotations)
<welcome-file-list> <welcome-file>/BaseServlet</welcome-file> </welcome-file-list>
The servlet spec says "A string containing only the '/' character indicates the "default" servlet of the application."
But it says straight afterwards
In this case the servlet path is the request URI minus the context path and the path info is null.
In other words, if your URL is
host
then the servlet path will be
"" (empty string)
so you will need a welcome file list (but index.htm[l] and index.jsp in the webapp directory, not WEB-INF, are included implicitly as a starting welcome file list)
回答2:
Edit:
If you want to pre-process then you can use Filter with url-pattern "/*" and dispatcher set to REQUEST that way it will ignore forward.
Last value "/" means all request.
Checkout discussion at: http://www.coderanch.com/t/366340/Servlets/java/servlet-mapping-url-pattern
And inside Servlet another forward request for index.html is generated which is also intercepted by servlet.
If you try @WebServlet({"/BaseServlet", "/"}) which is same as @WebServlet({"/BaseServlet", "", "/"}) will result in same error.
You can check this by typing following output statement in servlet:
System.out.println(req.getRequestURL());
来源:https://stackoverflow.com/questions/16578694/servlet-webservlet-urlpatterns