文章目录
1-请求转发和重定向
请求转发
请求转发的写法如下:
request.getRequestDispatcher("login_success.html").forward(request, response);
优劣点:
1、地址上显示的是请求servlet的地址 返回200 ok
2、请求次数只有一次,因为是服务器内部帮客户端执行了后续的工作
3、只能跳转自己项目的资源路径
4、效率上稍微高一点,因为只执行一次请求
5、可以使用上一次的request对象
重定向
重定向写法如下:重新定位方向 参数即跳转的位置
response.sendRedirect("login_success.html");
优劣点:
1、地址上显示的是最后的那个资源的路径地址
2、请求次数最少有两次,服务器在第一次请求后,会返回302以及一个地址,浏览器根据这个地址,执行第二次访问
3、可以跳转到任意路径,不止是自己的工程文件
4、效率稍微低一点,执行两次请求
5、后续的请求,没法使用上一次的request存储的数据,或者没法使用上一次的request对象,因为这是两次不同的请求
关于重定向,之前我是这么写的:
response.setStatus(302);
response.setHeader("Location","login_success.html");
那现在就可以直接用一行代替了
请求转发和重定向其实很好理解,可看下图:
2-Cookie介绍和简单使用
Cookie:其实就是服务器给客户端并储存在客户端上的一份小数据
应用场景:> 自动登录、浏览记录、购物车
问:为什么要有Cookie?
答:http的请求是无状态的,客户端与服务器在通讯的时候,是无状态的。其实就是客户端在第二次来访的时候,服务器根本就不知道这个客户端以前有没有来访问过。所i为了更好的用户体验,更好的交互[自动登录],所以要有Cookie要保存之前用户的数据,其实从公司层面讲,就是为了更好的收集用户习惯[大数据]。
Cookie的使用以及获取:
response.setContentType("UTF-8"); //设置编码,否则响应在页面的中文会乱码
Cookie[] cookies = request.getCookies(); //获得Cookies,有可能为空对象
if(cookies==null){ //若为空对象则添加一次
Cookie cookie = new Cookie("hpf","perfect"); //以key-value的形式保存
response.addCookie(cookie);
response.getWriter().write("Cookie添加成功!");
System.out.println("Cookie添加成功!");
}else{
for (Cookie cookie : cookies) { //遍历
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("Cookie:"+name+"="+value);
}
}
Cookie的常用API:
//关闭浏览器后,cookie就没有了 ---> 针对没有设置cookie的有效期
//expiry: 有效 以秒计算。
//正值: 表示在这个数字过后,cookie将会失效。
//负值: 关闭浏览器,那么cookie就失效, 默认值是 -1
cookie.setMaxAge(60 * 60 * 24 * 7); //使用Cookie对象来设置,表示七天有效期
//cookie.setValue(newValue); //赋值新的值
//用于指定只有请求了指定的域名,才会带上该cookie
cookie.setDomain(".itheima.com");
//只有访问该域名下的cookieDemo的这个路径地址才会带cookie
cookie.setPath("/CookieDemo");
3-Cookie获取上次登录时间
这里算是一个Cookie的综合例子,代码如下(主要部分):
login.html:
<body>
<h3>请登录</h3>
<form action="Demo03">
账号:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="登录">
</form>
</body>
CookieUtil:
//获取指定name的Cookie
public static Cookie getCookie(Cookie[] cookies,String name){
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)){
return cookie;
}
}
return null;
}
//清空当前浏览器的Cookie
public static Cookie[] clearCookie(Cookie[] cookies,HttpServletResponse response){
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
return cookies;
}
GetLastLoginTime:
response.setContentType("text/html;charset=UTF-8");
Date currenDate = null;
String currenTime = "";
String username = request.getParameter("username");
Cookie[] cookies = request.getCookies();
Writer writer = response.getWriter();
if(cookies!=null){
//获取上一次登录的时间
Cookie time = CookieUtil.getCookie(cookies, "time");
if(time!=null){
String value = time.getValue();
writer.write("欢迎"+username+"登录,上一次的登录时间为:"+value);
currenDate = new Date(System.currentTimeMillis());
currenTime = currenDate.toLocaleString();
time.setValue(currenTime);
time.setMaxAge(60*5);
response.addCookie(time);
}else{
CookieUtil.clearCookie(cookies,response);
response.setHeader("refresh", "3;login.html");
writer.write("Cookie已有数组,清空成功!");
}
}else{
currenDate = new Date(System.currentTimeMillis());
currenTime = currenDate.toLocaleString();
Cookie time = new Cookie("time", currenTime);
time.setMaxAge(60*5);
response.addCookie(time);
response.setHeader("refresh", "3;login.html");
writer.write("未找到Cookie,添加timeCookie成功!");
}
个人总结与心得:
1、login.html就不多说了,还是那么简单
2、setContentType这个方法里的字段,千万不能写错!!! text/html;charset=UTF-8
3、Writer这个东西,最好写一个对象出来,不然每次都要获取
4、虽然是第一次登陆,但也可能有之前的Cookie,所以要利用Util清空一下
5、清空完或者是添加完cookie,都要refresh到login.html
6、代码是代码,但不是一次性写出来的,都是一波三折,不一定要背,要知道思路!
4-Cookie商品浏览记录
首先,我先准备了一个商品页面的html,放在了WebContent里。
其次,再WebContent里新建了一个jsp文件,product_list.jsp,拷贝html里的内容到jsp中。
然后,再修改一下其中一件商品的跳转地址,改成product_list.jsp。
思考过程记录:
1、用户进入商品列表首页,还未选择商品,此时为第一次进入首页
2、用户选择了一次商品,jsp返回一个商品id,Servlet根据id记录Cookie
3、用户不是第一次进入首页,选择另一个商品,Servlet把本次id添加到上一次的Cookie中
Servlet中的代码如下:
String id = request.getParameter("id");
Cookie[] cookies = request.getCookies();
Cookie history = CookieUtil.getCookie(cookies, "history");
if(history==null){//第一次进网站,没有cookie保存
Cookie h = new Cookie("history",id);
h.setMaxAge(60*1);
//设置访问这个工程的时候,才带cookie过来
h.setPath("/CookieDemo02");
response.addCookie(h);
}else{//非第一次浏览,输出cookie并更新
System.out.println(history.getValue());
history.setValue(id+"#"+history.getValue()); //拼接Cookie
history.setMaxAge(60*1);
history.setPath("/CookieDemo02");
response.addCookie(history);
}
//跳转到具体的info页面
response.sendRedirect("product_info.htm");
这里介绍一下jsp,ava Server Pager —> 最终会翻译成一个类,就是一个Servlet。也就是说在jsp中可以写java的代码。
- 定义全局变量
<%! int a = 99; %> - 定义局部变量
<% int b = 999; %> - 在jsp页面上,显示 a 和 b的值
<%=a %>
<%=b %>
product_list.jsp中的Java代码如下:
<%
Cookie[] cookies = request.getCookies();
Cookie history = null;
if(cookies==null){
history = null;
}else{
history = CookieUtil.getCookie(cookies, "history");
}
String[] ids = null;
//若history为空的话
if(history==null){
%>
<h1>您的浏览记录为空!</h1>
<%
}else{
ids = history.getValue().split("#");
for(String id : ids){
%>
<li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;text-align: center;"><img src="products/<%=id%>.jpg" width="130px" height="130px" /></li>
<%
}
}
%>
注意:
第一对<%>中,如果不对cookies判断的话,有可能进入该页面就会报空指针错误,所以要判断。
下面就利用到了id来取到products目录下的图片文件。
所以以上所有代码实现的功能就是:进入商城并可以选择物品,最后能够查看浏览记录
实现删除浏览记录功能:
首先在浏览记录图片的div下方再写一个h2,h2中嵌套<a href=“ClearHistory”>清除浏览记录</a>
然后编写ClearHistory,其实很简单,主要代码如下:
Cookie[] cookies = request.getCookies();
Cookie history = CookieUtil.getCookie(cookies,"history");
Cookie cookie = new Cookie("history", "");
cookie.setMaxAge(0);
cookie.setPath("/CookieDemo02");
response.addCookie(cookie);
response.sendRedirect("product_list.jsp");
注意点总结:
1、删除cookie是没有什么delete方法的,只有设置maxAge为0
2、因为设置为0,本意是在浏览器关闭之后才清除,所以不能即时看见
3、删除的时候总是删除不掉,总的来说还是不够仔细,在History中,非第一次浏览添加Cookie时,忘记设置路径了,导致后面添加的Cookie都不是/CookieDemo02下面的,重点!!!
Cookie总结:
-
Cookie是服务器给客户端发送过来的一小份数据,并且存放在客户端上
-
获取cookie,添加cookie
request.getCookie(); response.addCookie();
-
Cookie分类
会话Cookie
默认情况下,关闭了浏览器,那么cookie就会消失持久Cookie
在一定时间内,都有效,并且会保存在客户端上cookie.setMaxAge(0); //设置立即删除 cookie.setMaxAge(100); //100 秒
-
Cookie的安全问题
1、由于Cookie会保存在客户端上,所以有安全隐患问题
2、而且,Cookie的大小与个数有限制,为了解决这个问题 —> 就引入了Session
5-Session介绍和简单使用
Session是基于Cookie的一种会话机制
Cookie与Session异同:
Cookie是服务器返回一小份数据给客户端,并且存放在客户端上,Session也是数据,但是存放在服务器端上
Session的常用API:
//得到会话ID
String id = session.getId();
//存值
session.setAttribute(name, value);
//取值
session.getAttribute(name);
//移除值
session.removeAttribute(name);
Session的声明周期:
创建:如果有在servlet里面调用了 request.getSession()这个方法,则就创建了Session
销毁:Session是存放在服务器的内存中的一份数据,即使关了浏览器,session也不会销毁
销毁途径:
1、关闭服务器
2、session会话时间过期,等有效期结束。默认有效期为30分钟
6-Session实现网页购物车
Session购物车例子(分析):
1、购物车这个例子的存储数据也可以用Cookie等来做,只不过用Session更安全
2、首先大致结构:商品页面->Count.Servlet->结算页面
3、其次就是,熟悉使用Session以及里面的方法即可
Session购物车例子(页面显示):
product_list.jsp:
<body>
<h1>请选择以下商品购买!</h1>
<a href="Count?id=0"><h3>iphone7</h3></a>
<a href="Count?id=1"><h3>小米10</h3></a>
<a href="Count?id=2"><h3>华为p30pro</h3></a>
<a href="Count?id=3"><h3>魅族3</h3></a>
<a href="Count?id=4"><h3>联想y7000p</h3></a>
<a href="Count?id=5"><h3>戴尔外星人</h3></a>
</body>
Count:
response.setContentType("text/html;charset=utf-8");
String[] names = {"iphone7","小米10","华为p30pro","魅族3","联想y7000p","戴尔外星人"}; //所有的商品名
Integer id = Integer.parseInt(request.getParameter("id")); //获取传过来的id
String name = names[id]; //取出id所对应的商品名
Writer writer = response.getWriter(); //获取输出流
HttpSession session = request.getSession(); //获得Session
Map<String, Integer> cart = (Map<String, Integer>)session.getAttribute("cart");
if(cart==null){ //以大化小,先化大的
cart = new LinkedHashMap<String, Integer>();
request.getSession().setAttribute("cart", cart);
}
if(!cart.containsKey(name)){ //第一次选择商品,并且购物车里面没东西
cart.put(name, 1);
}else{ //不是第一次选择商品,要叠加数量并显示
cart.put(name, (cart.get(name)+1));
}
writer.write("<a href='product_list.jsp'><h2>继续购物</h2></a>");
writer.write("<a href='cart.jsp'><h2>进行结算</h2></a>");
cart.jsp:
<body>
<h1>以下为所选商品以及数量</h1>
<%
Map<String,Integer> cart = (Map<String,Integer>)request.getSession().getAttribute("cart");
for(String name : cart.keySet()){
%>
<h3>商品名:<%=name %> 数量:<%=cart.get(name)%></h3>
<%
}
%>
<a href="ClearCart"><h2>清空购物车</h2></a>
</body>
Session购物车例子(清空购物车):
HttpSession session = request.getSession();
//写法二:移除整个session
session.invalidate();
//写法一:移除cart这个map
session.removeAttribute("cart");
response.sendRedirect("cart.jsp");
购物车例子总结:
1、让自己更加了解了Cookie以及Session的用法,受益颇多
2、关于Map的使用由不熟练而得到了巩固,还得加强
3、Count中添加商品的代码,我学会了以大化小的思想,先把大的(cart)判断了,再做小的(添加)
4、<%>的使用得到了加强,并且逐渐会使用jsp来编写页面代码,forEach循环也得到了加强
5、对Web项目的底层实现得到了深刻的了解与开发,并且感谢自己的努力!