从Java EE5.0开始,<servlet-mapping>标签就可以配置多个<url-pattern>。例如可以同时将urlServlet配置一下多个映射方式:
<servlet>
<servlet-name>servletName</servlet-name>
<servlet-class>com.copy.project.UrlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletName</servlet-name>
<url-pattern>/servlet/urlServlet</url-pattern>
<url-pattern>/servlet/urlServlet.asp</url-pattern>
<url-pattern>/servlet/urlServlet.jsp</url-pattern>
<url-pattern>/servlet/urlServlet.php</url-pattern>
</servlet-mapping>
这时,不加后缀和加.asp/.jsp/.php访问,都会正常显示。
项目中
web.xml中配置
<servlet>
<servlet-name>JSP Protect</servlet-name>
<servlet-class>com.companyname.web.JspProtect</servlet-class>
<init-param>
<param-name>prefix</param-name>
<param-value>/wp</param-value>
</init-param>
<init-param>
<param-name>suffix</param-name>
<param-value>.shtm</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>JSP Protect</servlet-name>
<url-pattern>*.shtm</url-pattern>
</servlet-mapping>
JspProtect类
1 private static final long serialVersionUID = -6821655106461234567L;
2
3 private String contextPath;
4 private String prefix;
5 private String suffix;
6
7 public void init(ServletConfig config) throws ServletException {
8 super.init(config);
9 contextPath = config.getServletContext().getContextPath();
10 prefix = StringUtils.defaultIfEmpty(
11 config.getInitParameter("prefix"), "");
12 suffix = StringUtils.defaultIfEmpty(
13 config.getInitParameter("suffix"), ".htm");
14 }
15 //项目中其他的类调用此方法会进行处理
16 public void execute(RequestContext context) throws Exception {
17 String toUrl = context.getRequest().getRequestURI();
18 toUrl = toUrl.replaceFirst(contextPath, prefix);
19 toUrl = toUrl.replace(suffix, ".jsp");
20
21 context.getRequest().getRequestDispatcher(toUrl).forward(context.getRequest(), context.getResponse());
22
23 }