JavaWeb--Cookie和Session小练习

一、前言

1、当登录一个网站时,网站往往会请求用户输入用户名和密码,并且用户可以勾选“下次自动登录”。如果勾选了,那么下次访问同一网站时,用户会发现没输入用户名和密码就已经登录了。这正是因为前一次登录时,服务器发送了包含登录凭据(用户名加密码的某种加密形式)的Cookie到浏览器,浏览器将cookie保存到了用户的硬盘上。第二次登录时,(如果该Cookie尚未到期)浏览器会发送该Cookie,服务器验证凭据,于是不必输入用户名和密码就让用户登录了。

2、通常我们在浏览网站时,有些页面是需要我们登陆之后才能浏览到的,其实这就用到了session

二、需求

现在通过一个简单的小例子来模拟这两个需求。

1、现有一个登陆页面,然后有两个可供浏览的页面,这两个页面的都是需要登陆之后才能访问;

2、在提交登陆请求后需要进行身份验证,验证通过后跳到指定页面;如果未通过则重新回到登录页面,并显示错误信息“用户名或密码输入错误!”;

3、在第一次登录时需要输入用户名和密码,但是第一次之后则不用输入用户名;

4、如果用户想要直接使用供浏览页面的url来访问这两个页面,则跳转到登录页面,并提示“请先登录!”。

三、需求分析

(一)其流程图大概如下:

(二)其各部分功能如下

login.jsp:

1、提供登录表单
2、表单提交至loginServlet
3、如果身份验证失败,需要显示错误信息
4、如果是因为直接访问从而跳转到登录页面,也需要显示错误信息
5、第一次登录之后不需要输入用户名

loginServlet:

1、需要处理乱码问题
2、获取用户信息
3、对用户信息进行验证
4、如果验证成功:
	a、在cookie中保存用户信息
	b、在session域保存用户信息,并且显示指定页面
5、如果验证失败:
	a、在request域中设置错误信息,并且跳转到登录页面

succ1.jsp:

1、判断用户是否登录
	a、如果已经登录,则显示页面信息
	b、如果没有登录,则在request中设置错误信息,并且跳转到登录页面
2、提供页面相关信息(succ2.jap的链接)

succ2.jsp:

1、判断用户是否登录
	a、如果已经登录,则显示页面信息
	b、如果没有登录,则在request中设置错误信息,并且跳转到登录页面
2、提供页面相关信息(succ1.jap的链接)
(三)该案例中使用request域和request的请求转发,以及session域和cookie的具体地方

注意:一定要尽可能的使用更小的域!

四、代码实现

(一)目录结构

(二)源代码

login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>	<%-- 导包 --%>
<%@ page import="java.net.URLDecoder" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'login.jsp' starting page</title>
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
 	<h1>登录</h1>
 	<%-- 显示错误信息 --%>
 	<%
 		String msg = "";
 		String str = (String)request.getAttribute("msg");
 		if(str != null){
 			msg = str;
 		}
 	%>
 	<font color="red"><b><%= msg %></b></font>
 	
 	<%-- 登录时,可以从cookie中获取用户名 --%>
 	<%	
 		String userName="";
 		Cookie[] cs = request.getCookies();	//遍历cookie所有cookie的值,查看是否有键为userName的cookie、
 		if(cs != null){
 			for(Cookie c:cs){
 				if("userName".equals(c.getName())){//有键为userName的cookie、
 					userName = URLDecoder.decode(c.getValue(), "utf-8");
 					break;
 				}
 			}
 		}
 	%>
 	
 	<%-- 提供表单 --%>
    <form action="/day11_3/LoginServlet" method="post">
    	用户名:<input type="test" name="userName" value="<%= userName %>"/><br/><br/>
    	密    码:<input type="password" name="pwd"/><br/><br/>
    	<input type="submit" value="登录"/> 
    </form>
  </body>
</html>

loginServlet:

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;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 1、处理乱码问题
		 * 2、获取请求参数
		 * 3、进行用户信息校验
		 * 	4、正确
		 * 		a、保存cookie,内容为用户名
		 * 		b、在session中加入用户信息,然后重定向到succ1.jsp
		 * 	5、如果错误,则在request域中设置错误信息,然后转发到login.jsp重新登录,并显示错误信息
		 */
		request.setCharacterEncoding("UTF-8");
		
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		
		boolean noNull = (userName!=null)&(pwd!=null);	 //用户名和密码不为空
		boolean flag1 = "张三".equals(userName);		   //用户名正确
		boolean flag2 = "123456".equals(pwd);			//密码正确
		boolean coorect = flag1&flag2;
		
		if(noNull&coorect){	 //验证成功
			//保存cookie
			Cookie cookie = new Cookie("userName", URLEncoder.encode(userName, "utf-8"));
			cookie.setMaxAge(60*60*24);
			response.addCookie(cookie);
			
			//获取session,然后添加用户信息
			HttpSession session = request.getSession();
			session.setAttribute("userName", userName);
			//重定向到succ1
			response.sendRedirect("/day11_3/session2/succ1.jsp");
		}else{	//验证失败
			//在request域中添加错误信息
			request.setAttribute("msg", "用户名或密码输入错误!");
			//转发到login.jsp
			request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
		}
	}
}

succ1.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'succ1.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="-1">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<%-- 判断是否为登录状态:看session中是否有用户信息 --%>
    <%
    	String userName = (String)session.getAttribute("userName");
    	if(userName == null){	//非登录状态,设置错误信息,并重定向到登录界面
    		request.setAttribute("msg", "请先登录!");
    		request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
    		return;
    	}
    %>
    
    <h2><%= userName %>, 登录成功!</h2>
    <h1>我是succ1页面</h1><br/><br/>
    <h1><a href="/day11_3/session2/succ2.jsp">浏览succ2</a></h1>
  </body>
</html>

succ2.jsp:和succ1.jsp只有最后两个h1标签不一样

<h1>我是succ2页面</h1><br/><br/>
<h1><a href="/day11_3/session2/succ1.jsp">浏览succ1</a></h1>
五、测试结果

1、在浏览器中输入:http://localhost:8080/day11_3/session2/login.jsp

2、登陆失败:

3、登陆成功后:

4、通过“浏览succ2链接”访问succ2:

5、尝试直接使用succ1的链接地址来访问:

6、第二次登陆:

六、需要注意的地方

(一)Cookie需要处理中文

Cookie使用Unicode字符时需要对Unicode字符进行编码。

设置Cookie时:
Cookie cookie = new Cookie("userName", URLEncoder.encode(userName, "utf-8"));

获取Cookie时:
userName = URLDecoder.decode(c.getValue(), "utf-8");

(二)在jsp中进行Cookie进行解码时,记得导包
<%@ page import="java.net.URLDecoder" %>

七、Cookie和Session的基础知识

1、Cookie:介绍会话技术、Cookie的API、详解、应用

2、Session:Session介绍、API、生命周期、应用、与Cookie区别

Java新手,若有错误,欢迎指正!

猜你喜欢

转载自www.cnblogs.com/Java-biao/p/12724740.html
今日推荐