java web 学习笔记

来源:互联网 发布:罗辑思维的骗局 知乎 编辑:程序博客网 时间:2024/05/20 22:36

  1.Servlet可以分为三种类型

  普通Servlet,需要在基本程序架构中体现。

  Servlet过滤器,在web容器启动时初始化,不需要手动调用。

  Servlet 监听器。

  2. Servlet过滤器, 过滤器可以有多重过滤

  a.可以编码过滤。替掉了每页

  b.可以登录验证。在一个会话中(只启动一次浏览器),如果登录过,那么访问其他网页则可直接访问。

  如果另外开启一个会话,那么访问其他网页服务器将直接跳转到登录页面。

  关键记忆点:

  a. web.xml中不再是而是,内容如下:

  login

  cn.liys.filter.LoginFilter

  login

  /filter/* //相当于对于这个目录下所有的页面都其过滤作用

  b. 类的申明与servlet有所不同,是实现一个Filter接口

  pulbic class LoginFilter implements Filter{

  private String charset = null;

  public void init(FileConfiger config){

  charset = config.getInitParamter("charset");

  }

  public voild doFilter(ServletRequest request ,ServletResponse response, FilterChain chain ){

  request.setCharacterEncoding(charset); //设置编码;

  HttpServletRequest req = (HttpServletRequest ) request;

  HttpSession ses = req.getSession();

  if (ses.getAttribute("userid")!=null){ //登录过进入到下一个页面

  chain.doFilter(req,response); //过滤后,允许进入下一个页面。一般每次刷新都会过滤。

  }else{ //没登录过,重新定位到登录界面

  req.getRequestDispatcher("login.jsp").forward(request,response); //如果没有登陆,则重定位到登陆界面

  }

  }

  public void destroy(){

  }

  }

  3.Servlet监听器

  a.可以监听application ,session ,request这些宝坻全屋定制内置对象的相关操作,具体可以查java doc,基本都是interface 接口实现。

  b.实际项目可以用到显示当前在线人员

  思路,要让所有人看到当前在线人员,必须是通过application内置对象保存,所有的在线人员应该是一个集合,可以是TreeSet

  等一个用户登录后,肯定是在session内置对象中增加一个userid,当这个回话过了超时时间,将删掉该用户名。

  这样这个监听类,需要实现ServletContextListener,HttpSessionAttributeListener,HttpSessionListener这三个接口

  关键代码如下

  ====================================================================================================

  监听类:

  public class OnlineListener implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener{

  // 需要把这些接口的抽像函数都列出来,不实现可以空着。

  private ServletContext app = null;

  public void contextInitialized(ServletContextEvent sce){ //application初始化时

  this.app = sce.getServletContext();

  this.app.addAttribute("online",new TreeSet());

  }

  。。。。

  public void attributeAdded(HttpSessionBindingEvent se){//登录时Session需要设置用户id

  Set all =(Set) this.app.getAttribute("online");

  all.add(se.getValue());

  this.app.addAttribute("online",new TreeSet());

  }

  public void sessionDestroyed(HttpSessionEvent se){//会话超时,从application保存的集合中删除用户名

  Set all = (Set) this.app.getAttribute("online") ;

  all.remove(se.getSession.getAttribute("userid"));

  this.app.addAttribute("online",new TreeSet());

  }

  }

  Web.xml中的配置: (监听主要是监听application,request,session这些对象,所以不需要其他的参数配置,比如路径等)