JavaWeb学习笔记①——Java向下转型在JavaEE中运用——登陆验证
在学习JavaEE的过程中慢慢了解到Java中编程思想的优秀设计,以下将是一个多态-向下转型的示例,该实例是在Servlet-过滤器中的登陆验证的示例,代码中运用向下转型解决问题
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletReponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class LoginFilter implements Filter{ public void init(FilterCOnfig config) throws ServletException{ } public void doFilter(ServletRequest request, ServletResponse response, Filter chain) throws IOException, ServletException{ HttpServletRequest req = (HttpServletRequest) request; //向下转型 HttpSession ses = req.getSession(); //取得session if(ses.getAttribute("useid") != null){ //判断是否登录 chain.doFilter(request, response); //传递请求 }else{
request.getRequestDispatcher("login.jsp").forward(request, response); //转到登陆页 } } public void destory(){ //销毁过滤 } }
session本身是术语HTTP协议的范畴,但是doFilter()方法中定义的事ServletRequest类型的对象,那么要想取得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能通过getSession()方法取得session对象。