会话:简单来说,用户访问一个浏览器,在浏览器上执行了很多操作,访问多个页面最后关闭浏览器,这个过程称为会话。
cookie 存在于浏览器的本机 ,使用者可以看到cookie里边的内容,不安全
Cookie cookie=new Cookie("info", name);cookie.setMaxAge(-1);//0表示删除该cookie,-1表示保存到浏览器关闭,别的事表示秒
response.addCookie(cookie);
response.getWriter().println(cookie.getName()+":"+cookie.getValue());
session存在于服务器中,使用者只能看到健K,不能看到value
常用session
HttpSession session= request.getSession();
session.setAttribute("info", name);
response.getWriter().println(request.getSession().getAttribute("info"));
Servlet生命周期
Servlet是运行在服务器端的一段程序,所以Servlet的生命周期会受Servlet容器的控制。Servlet生命周期包括加载、初始化、服务、销毁、卸载等5个部分,如图,
图4-07
通常情况,加载和卸载阶段可以由Servlet容器来处理,我们只需要关注初始化、服务、销毁三个阶段。与Servlet生命周期相关的方法,如下表,
方法 | 简介 |
public void init() throws ServletException | Servlet初始化时调用 |
public void init(ServletConfig config) throws ServletException | init() 的重载方法,Servlet初始化时调用,并可以通过config来读取配置信息 |
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; | 提供Servlet服务的方法。此方法是抽象方法,故实际使用的是此抽象方法的实现方法doGet()或doPost()来处理get或post请求 |
public void destroy() | Servlet销毁时调用 |
过滤器Filter(编码拦截)
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
chain.doFilter(request, response);//当有多个filter的时候,交给后面的filter方法,就是一条过滤链