从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     }

 





相关文章:

  • 2021-08-25
  • 2022-12-23
  • 2021-09-10
  • 2021-12-14
  • 2021-08-13
  • 2021-06-18
  • 2022-12-23
猜你喜欢
  • 2022-02-10
  • 2021-06-24
  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2022-02-20
  • 2021-06-11
相关资源
相似解决方案