public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException,ServletException
{
//获取该Filter的配置参数
String encoding = config.getInitParameter("encoding");
String loginPage = config.getInitParameter("loginPage");
String proLogin = config.getInitParameter("proLogin");
//设置request编码用的字符集
request.setCharacterEncoding(encoding); //①
HttpServletRequest requ = (HttpServletRequest)request;
HttpSession session = requ.getSession(true);
//获取客户请求的页面
String requestPath = requ.getServletPath();
这样的情景,在filter里面总会看到,为啥要强制转换呢?经过测试知道了,if(request instanceOf HttpServletRequest) System.out.println("true");输出true。
ServletRequest是HttpServletRequest的父接口,可见request是HttpServletRequest的实现类的对象,下面就会用到多态的知识,
ServletRequest request;这个是将子类对象赋给父类引用,他运行时的类型是子类,编译时的类型是父类,但是在运行时,父类类型对象调用的方法如果子类里面有,那就执行子类里面的方法,如果编译时的类型也就是父类没有调用的那个方法,则报错。所以在那里要做一个强制类型转换,否则就会报错。