你可以编写一个过滤器来拦截请求,在过滤器中检查请求的url是否为'/',如果是,则将请求转发到欢迎页面。
public class MyFilter implements Filter {
private ServletContext servletContext;
public void init(FilterConfig config) throws ServletException {
servletContext = config.getServletContext();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String path = ((HttpServletRequest)request).getPathInfo();
if(path.equals("/")){
servletContext.getRequestDispatcher("/welcome.jsp").forward(request, response);
} else {
chain.doFilter(request,response);
}
}
}
在 web.xml 中应用过滤器:
<filter>
<filter-name>welcomeFilter</filter-name>
<filter-class>the filter class</filter-class>
</filter>
<filter-mapping>
<filter-name>welcomeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>