首页 > 代码库 > 利用filter过虑用户请求URI显示对应页面内容

利用filter过虑用户请求URI显示对应页面内容

目的:只是想验证一下filter对URI的过滤

流程讲解:浏览器请求URI,所有请求都走过虑器,在过滤器中处理符合某种请求的URI然后显示对应的页面内容

有2个JSP页面:

index.jsp:

  <body>
    This is index page. 111111111111111111111<br>
    <ul>
        <li>1111111111</li>
        <li>2222222222</li>
    </ul>
  </body>

select.jsp:

<body>
     <ul>
        <li>3333333</li>
        <li>444444444</li>
    </ul>
  </body>

filter类UrlFilter.java

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;
        HttpServletResponse httpServletResponse=(HttpServletResponse) response;
        String requestUrl = httpServletRequest.getRequestURI();
        String ContextPath =httpServletRequest.getContextPath();
        System.out.println(requestUrl+"========"+ContextPath);
        String ContextPath1=ContextPath+"/";
        String uri=requestUrl.replace(ContextPath1, "");
        System.out.println("uri==========="+uri);
        
        //String info = uri.substring(0, uri.indexOf("."));
        if("index".equals(uri)){
            httpServletRequest.getRequestDispatcher("index.jsp").forward(httpServletRequest, httpServletResponse);
        }else if("select".equals(uri)){
            httpServletRequest.getRequestDispatcher("select.jsp").forward(httpServletRequest, httpServletResponse);
        }
    }

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
 
  <filter>
      <filter-name>urlFilter</filter-name>
      <filter-class>filter.UrlFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>urlFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

浏览器访问uri:

1、http://localhost:8080/struts/index显示index.jsp页面内容

2、http://localhost:8080/struts/select显示select.jsp页面内容

利用filter过虑用户请求URI显示对应页面内容