一、cookie和session
1.业务场景
- 登录时要记录帐号
- 以后访问查询、增加、修改页面时要显示帐号
2.前提条件
- 浏览器和服务器是多对一的关系
3.错误的做法
request
- 登录、查询是不同的请求,使用不同的request
- 2个请求服务器创建2个request,所以无法通过request共享这样的数据
config
- 假设开发项目时采用多个Servlet处理不同请求
- 登录有一个Servlet,查询有一个Servlet
- 多个Servlet用不同的config
它没有读写变量的能力
context
- tomcat内只有一个对象
- 每个用户登录时传入的数据都是code=xxx
- 其中key都一样,存入时context有冲突
- 若将这样的数据存入唯一的context是有冲突的
4.正确的做法(*)
- 使用cookie或session来保存这样的数据
5.它们的区别(*)
- cookie存储在浏览器上,服务器压力小,但数据不安全
- session存储在服务器上,服务器压力大,但数据安全
6.如何选择
- 重要数据存入session
- 一般数据存入cookie
二、cookie
1.演示案例
LoginServlet代码
package web;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 登录检查,判断密码是否正确
*/
public class LoginServlet extends HttpServlet {
//模拟MainServlet.login()
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//接受参数(帐号密码)
String user = req.getParameter("user");
//检查帐号密码
//转发重定向
//检查通过后,将账号存入cookie
//cookie中只能存一条数据,
//并且只能存字符串.
Cookie c1 = new Cookie("user",user);
//声明cookie的生存时间
//>0时,cookie保存在客服端的硬盘上
//=0时cookie被浏览器删除
//将cookie存到硬盘上
c1.setMaxAge(600000);
//设置cookie的有效路径
c1.setPath("/Jsp4");
//将cookie绑定到response上,
//当服务器发送响应时会自动发送cookie.
res.addCookie(c1);
//再创建一个cookie,存入中文
Cookie c2 = new Cookie("city",URLEncoder.encode("北京", "utf-8"));
res.addCookie(c2);
}
}
IndexServlet代码
package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 模拟打开主页
*/
public class IndexServlet extends HttpServlet {
//模拟MainServlet.toIndex()
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//浏览器访问服务器时,会自动传入
//之前保存的cookie.
//获取cookie
Cookie[] cs = req.getCookies();
//将他们也输出给浏览器
if(cs != null) {
res.setContentType("text/html;charset=utf-8");
PrintWriter w = res.getWriter();
for(Cookie c : cs) {
String value = URLDecoder.decode(c.getValue(), "utf-8");
w.println(c.getName()+":"+value);
}
w.close();
}
}
}
web.xml配置文件代码
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/main/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>web.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/main/index</url-pattern>
</servlet-mapping>
结果
FindCostServlet代码
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 模拟查询资费
*/
public class FindCostServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//模拟查询资费(略)
//获取cookie中的帐号,并输出
Cookie[] cookies = req.getCookies();
if(cookies != null) {
res.setContentType("text/html;charset=utf-8");
PrintWriter w = res.getWriter();
for(Cookie c : cookies) {
w.println(c.getName()+":"+c.getValue());
}
w.close();
}
}
}
web.xml加上
<servlet>
<servlet-name>findCost</servlet-name>
<servlet-class>web.FindCostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>findCost</servlet-name>
<url-pattern>/cost/find</url-pattern>
</servlet-mapping>
结果
2.特点
- cookie保存在浏览器上
- 多个请求可以共用一组cookie
- 多个Servlet可以共用一组cookie
- 每个用户(浏览器)访问服务器,都会获得一组cookie
3.要点
- 如何创建cookie——————–Cookie c1 = new Cookie(“code”,code);
- 如何获取/修改cookie————–Cookie[] cs = req.getCookies();/req.setCookies();
- 如何修改cookie的生存时间——-c1.setMaxAge(600000);
- 如何向cookie存中文—————Cookie c2 = new Cookie(“city”,URLEncoder.encode(“北京”,”utf-8”));
- 如何修改cookie的生存路径——-c1.setPath(“/jsp4”);
三、session
1.演示案例
LoginServlet代码
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//接收帐号
String user = req.getParameter("user");
//首次调用session时服务器会自动给
//当前访问的浏览器创建一个session
//该session是jsp的隐含对象之一
HttpSession session = req.getSession();
//session中可以存任意类型的数据
session.setAttribute("user", user);
//服务器响应时会作出如下处理:
//Cookie c = new Cookie(
// "JSESSIONID",session.getId());
//c.setPath(request.getContextPath());
//response.addCookie(c);
}
}
IndexServlet代码
package web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class IndexServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//本次请求中,浏览器会自动传入事先保存的JSESSIONID,然后
//服务器根据此ID找到旧的session
HttpSession session = req.getSession();
String user = (String)session.getAttribute("user");
//将此数据显示给浏览器
res.setContentType("text/html;charset=utf-8");
PrintWriter w = res.getWriter();
w.println(user);
w.close();
}
}
web.xml代码
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/main/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>web.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/main/index</url-pattern>
</servlet-mapping>
<!-- session超时销毁 -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
结果
- 登录后走开,判断有没有超时,如果超时会自动销毁session,时间可以通过web.xml配置文件修改
2.特点(*)
- 浏览器第一次访问服务器时,服务器会给它创建一个session
- 服务器会使cookie将SID返回给浏览器
- 浏览器再次访问服务器时会传入SID
- 多个请求可以共用一个session
- 多个Servlet可以共用同一个session
- 服务器会给每个浏览器创建1个session
3.退出功能(销毁session)
四、cookie和session的作用
1.通俗的描述(理解)
- 它们内部存储的数据满足如下规则:
- 这些数据在不同的请求中可以共用
- 这些数据在不同的Servlet之间可以共用
- 每个浏览器都有一组这样的数据
2.专业的描述(背)
- HTTP协议是无状态协议,即服务器没有记住浏览器
- cookie和session就是用来管理状态,让服务器记住浏览器
状态:浏览器曾经访问过服务器的证据(数据)
五、过滤器
1.过滤器的作用
- 用来处理项目中的公共的需求
- 举例:记录日志、过滤敏感词、权限检查
公共的需求:很多请求都包含的业务
2.过滤器开发步骤
- 创建一个类,实现过滤器接口Filter
- 在web.xml里配置这个类
过滤器由服务器自动调用
3.小案例(用来做登录检查,判断用户是否登录)
LoginFilter代码
package web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 用来做登录检查,判断用户是否登录。
*/
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//1.先明确校验的范围,
//有3个请求不必判断:
//toLogin.do,createImg.do,login.do
String[] paths = new String[]{"/toLogin.do","/createImg.do", "/login.do"};
//当前路径
String path = request.getServletPath();
//若当前路径是上诉三个路径之一
for(String p : paths) {
if(p.equals(path)) {
//不必过滤,请求继续执行
chain.doFilter(req, res);
return;
}
}
//2.如果不是上述范围内的路径,
//则是我们要做登录检查的目标。
//从session中尝试获取帐号
HttpSession session = request.getSession();
String adminCode = (String)session.getAttribute("adminCode");
//根据帐号判断用户是否登录
if(adminCode == null) {
//没登录,重定向到登录页
response.sendRedirect("/Netctoss/toLogin.do");
} else {
//已登录,放行
chain.doFilter(request, response);
}
}
public void init(FilterConfig arg0)
throws ServletException {
}
}
web.xml代码
<!-- 登录检查过滤器 -->
<filter>
<filter-name>login</filter-name>
<filter-class>web.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
结果
如果没登录,会自动跳转到登录界面
六、监听器
1.什么是监听器
- 监听器用来监听事件,当某事件发生时,它会通知服务器
- 它监听的目标是一些对象
2.监听器的分类(接口)
1) request
- 创建与销毁:ServletRequestListener
- 数据的变化:ServletRequestAttributeListener
2) session
- 创建与销毁:HttpSessionListener
- 数据的变化:HttpSessionAttributeListener
3) context
- 创建与销毁:ServletContextListener
- 数据的变化:ServletContextAttributeListener
3.开发步骤
- 创建一个类,实现对应的监听器接口
- 在web.xml中声明此类
4.案例
AddCostServlet代码
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddCostServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
System.out.println("增加资费");
req.setAttribute("user", "zhangsan");
}
}
GuolvFilter代码(过滤)
package web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class GuolvFilter implements Filter {
public void destroy() {
System.out.println("销毁GuolvFilter");
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
System.out.println("在前面过滤敏感词");
chain.doFilter(request, response);
System.out.println("在后面过滤敏感词");
}
public void init(FilterConfig cfg) throws ServletException {
System.out.println("初始化GuolvFilter");
String city = cfg.getInitParameter("city");
System.out.println(city);
}
}
LogFilter代码(记日志)
package web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LogFilter implements Filter {
//关闭tomcat自动调用此方法
public void destroy() {
System.out.println("销毁LogFilter");
}
//公共的业务在此处实现
//Filter相当于Servlet的管家,tomcat在调用Servlet之前会将请求
//提交给Filter,Filter有权让请求继续,也有权让请求终止
//tomcat就是调用doFilter方法让Filter统一处理请求,调用前创建
//好request和response并传入,创建类型:
//RequestFacade和ResponseFacade
public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("在前面记日志");
//请求继续,向下执行
chain.doFilter(request, response);
System.out.println("在后面记日志");
}
//tomcat启动时会自动实例化Filter,然后调用init()来初始化Filter
//调用此方法时回传入config,该对象和Filter是1对1的关系,可以给
//Filter预置参数(web.xml),该对象和SerlvetConfig用法完全一样
public void init(FilterConfig arg0) throws ServletException {
System.out.println("初始化LogFilter");
}
}
MyListener代码(监听器)
package web;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyListener implements
ServletRequestListener,
ServletRequestAttributeListener {
//tomcat销毁request前自动调用
public void requestDestroyed(ServletRequestEvent arg0) {
System.out.println("request销毁");
}
//tomcat创建request后自动调用
public void requestInitialized(ServletRequestEvent e) {
System.out.println("request创建");
System.out.println(e.getServletRequest());
}
public void attributeAdded(ServletRequestAttributeEvent arg0) {
System.out.println("向request中添加数据");
}
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
}
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
}
}
web.xml配置文件代码
<servlet>
<servlet-name>addCost</servlet-name>
<servlet-class>web.AddCostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addCost</servlet-name>
<url-pattern>/addCost</url-pattern>
</servlet-mapping>
<filter>
<filter-name>log</filter-name>
<filter-class>web.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>log</filter-name>
<!-- 声明此filter可以过滤哪些请求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>guolv</filter-name>
<filter-class>web.GuolvFilter</filter-class>
<init-param>
<param-name>city</param-name>
<param-value>北京</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>guolv</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>web.MyListener</listener-class>
</listener>