Servlet @WebServlet urlPatterns

This is a quick question, but I could not find a quick answer. Now I have a BaseServlet servlet when a user requests any of the following links:

host host/ host/BaseServlet 

It should always link to the same servlet and redirect to the home page.

When i install

 @WebServlet({"/BaseServlet", ""}) 

Only

 host/ host/BaseServlet 

work

If i installed

 @WebServlet({"/BaseServlet", "", "/"}) 

BaseServlet will be queried continuously in a loop ...

Why?

Edit: BaseServlet makes forward to index.html hidden in the WEB-INF folder and that it is.

 getServletContext().getRequestDispatcher("/WEB-INF/index.html").forward(request,response); 

The servlet specification says: "A string containing only the / character indicates the" servlet "by default of the application." Therefore, I want BaseServlet to be my default. Why is this not working?

+7
source share
2 answers
  • 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 cannot specify welcome files using annotations)

     <welcome-file-list> <welcome-file>/BaseServlet</welcome-file> </welcome-file-list> 
  • The servlet specification says: "A line containing only the" / "character indicates the" servlet "by default of the application."

    But he speaks right after

    In this case, the servlet path is the request URI minus the context path and the path information is zero.

    In other words, if your url is

     host 

    then the servlet path will be

     "" (empty string) 

    so you need a list of welcome files (but index.htm [l] and index.jsp in the webapp directory, and not in WEB-INF, are implicitly included as a start list of welcome files)

+10
source

Edit:

If you want to pre-process, you can use Filter with the url-sample "/ *" and the dispatcher configured for the REQUEST so that it ignores the forward.

The last value "/" means the entire request.

Discussion of issues at: http://www.coderanch.com/t/366340/Servlets/java/servlet-mapping-url-pattern

And inside the Servlet, another forward request is generated for index.html, which is also intercepted by the servlet.

If you try @WebServlet ({"/ BaseServlet", "/"}), the same as @WebServlet ({"/ BaseServlet", "", "/"}) will result in the same error.

You can verify this by entering the following output statement in the servlet:

 System.out.println(req.getRequestURL()); 
+2
source

All Articles