当我们访问一个web项目时,仅仅输入项目名,默认会转向index.jsp,如果要使其转向默认的servlet,我们需要定义一个过滤器来实现。
<filter> <filter-name>dispatcher</filter-name> <filter-class>com.siya.util.Dispatcher</filter-class> </filter> <filter-mapping> <filter-name>dispatcher</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
在过滤器中就可以对访问的url进行判断了。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse resp=(HttpServletResponse) response; String reqUrl=req.getRequestURL().toString(); if(reqUrl.endsWith("/")){reqUrl=reqUrl.substring(0, reqUrl.length()-1);} String context=req.getContextPath(); String temurl=reqUrl.substring(reqUrl.lastIndexOf("/")+1); if(reqUrl.endsWith(context)){ req.getRequestDispatcher("默认的servlet地址").forward(req, resp); }else{ req.getRequestDispatcher(temurl).forward(req, resp); } }