1.經常使用操做:javascript
package cn.zzsxt.lee.web.cookie; import java.io.IOException; 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 GetCookieServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 獲取cookie信息 Cookie[] cookies = req.getCookies(); for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].getName() + ":" + cookies[i].getValue()); } } }
package cn.zzsxt.lee.web.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @description * * cookie: * 在服務器被建立,返回給客戶端,而且保存客戶端 * 若是設置了SETMAXAGE(int seconds),會把cookie保存在客戶端的硬盤中 * 若是沒有設置,會默認把cookie保存在瀏覽器的內存中 * 一旦設置setPath():只能經過設置的路徑才能獲取到當前的cookie信息 * @author Seven Lee * @date * */ @WebServlet("/cookie.sxt") public class CookieServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 建立cookie對象 Cookie compCookie = new Cookie("computer", "HP"); // 服務器把cookie響應給客戶端,全部的cookie對象,都會在服務器端建立,經過http響應給客戶端(瀏覽器) Cookie keyCookie = new Cookie("key", "doubleflybird"); Cookie mouseCookie = new Cookie("mouse", "leishe"); mouseCookie.setMaxAge(60*60*24*30);//若是不設置使用時間,那麼將取不到Cookie的值 System.out.println(req.getContextPath());// 項目名(在tomcat中部署的項目名) // /zzsxt/shopping.jsp keyCookie.setPath(req.getContextPath()+"/getCookie.sxt");// 一旦設置了cookie的路徑,就只能經過這一個路徑才能獲取到cookie信息 resp.addCookie(compCookie); resp.addCookie(mouseCookie); resp.addCookie(keyCookie); } }
2.Cookie和Session登陸實例:html
註冊:java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'register.jsp' starting page</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> var sexFlag = false; var untFlag = false; function checkSex() { var sex = $(":checked").val(); if (sex != null) { // 驗證成功 alert(111); sexFlag = true; } else { // 驗證失敗 alert(222); sexFlag = false; } } function checkUniversity() { var unt = $(":selected").val(); if (unt != 0 && unt != null) { // 驗證成功 untFlag = true; } else { untFlag = false; } } $(function() { $("form").submit(function() { checkSex(); checkUniversity(); return sexFlag && untFlag; }); }); </script> </head> <body> <h1>註冊頁面</h1> <form action="register.sxt" method="post"> 用戶名: <input type="text" name="username" id="uname" /> 密碼: <input type="password" name="pwd" id="pawd" /> 性別: <input class="sexes" type="radio" name="sex" value="male" /> 男 <input class="sexes" type="radio" name="sex" value="female" /> 女 院校:<select name="unt"> <option value="0">請選擇院校</option> <option value="zzsxt">天津大學</option> <option value="bjsxt">北京大學</option> </select> <input type="submit" value="提交" /> </form> </body> </html>
註冊處理:jquery
package cn.zzsxt.lee.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.zzsxt.lee.web.dao.IUserDao; import cn.zzsxt.lee.web.dao.impl.UserDaoImpl; import cn.zzsxt.lee.web.entity.User; import cn.zzsxt.lee.web.utils.BASE64; import cn.zzsxt.lee.web.utils.MD5; import cn.zzsxt.lee.web.utils.UUIDUtils; @WebServlet("/register.sxt") public class RegisterServlet extends HttpServlet { private IUserDao userDao = new UserDaoImpl(); @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); String sex = request.getParameterValues("sex")[0]; String university = request.getParameterValues("unt")[0]; User user = new User(); user.setId(UUIDUtils.getUUid()); user.setUsername(username); user.setRealPassword(pwd); pwd = MD5.getMD5(pwd); user.setPassword(pwd); user.setSex(sex); user.setUniversity(university); user.setAuthority(0); int result = 0; try { result = userDao.registerUser(user); } catch (Exception e) { e.printStackTrace(); } if (result > 0) { response.sendRedirect("login.jsp"); return; } } }
登陸以前必須先判斷獲取Cookie:web
package cn.zzsxt.lee.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.zzsxt.lee.web.utils.MD5; @WebServlet("/checkLogin2.sxt") public class CheckLogin2 extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = ""; String password = ""; // 1.獲取cookie的值 Cookie[] cookies = request.getCookies(); // 2.判斷cookie數組是否爲null if (cookies != null) { // 3.判斷cookie中是否有用戶名和密碼 for (int i = 0; i < cookies.length; i++) { if ("uname".equals(cookies[i].getName())) { // 4.若是cookie中有用戶名和密碼,就獲取 username = cookies[i].getValue(); } if ("pwd".equals(cookies[i].getName())) { password = cookies[i].getValue(); } } } request.getSession().setAttribute("name", username); request.getSession().setAttribute("pwd", password); response.sendRedirect("login.jsp"); return; } }
登陸:數組
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'login.jsp' starting page</title> </head> <body> <form action="login.sxt" method="post"> 用戶名: <input type="text" name="username" value="${name }" /> 密碼: <input type="password" name="pwd" value="${pwd }" /> <input type="submit" value="提交" /> </form> </body> </html>
登陸處理:瀏覽器
package cn.zzsxt.lee.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.zzsxt.lee.web.dao.IUserDao; import cn.zzsxt.lee.web.dao.impl.UserDaoImpl; import cn.zzsxt.lee.web.entity.User; import cn.zzsxt.lee.web.utils.MD5; @WebServlet("/login.sxt") public class LoginServlet extends HttpServlet { private IUserDao userDao = new UserDaoImpl(); @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); pwd = MD5.getMD5(pwd); User user = new User(); user.setUsername(username); user.setPassword(pwd); try { User u = userDao.selectUserByUsernameAndPassword(user); if (u.getId() != null && !"".equals(u.getId())) { // 登陸成功 // 存入session request.getSession().setAttribute("user", u); Cookie usernameCookie = new Cookie("uname", u.getUsername()); Cookie pwdCookie = new Cookie("pwd", u.getRealPassword()); usernameCookie.setMaxAge(60 * 60 * 24); pwdCookie.setMaxAge(60 * 60 * 24); response.addCookie(usernameCookie); response.addCookie(pwdCookie); response.sendRedirect("index.jsp"); } else { // 登陸失敗 } } catch (Exception e) { e.printStackTrace(); } } }
frameset框架主頁:tomcat
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <frameset rows="100,*"> <frame src="top.jsp" name="top" /> <frameset cols="200,*"> <frame src="left.jsp" name="left" /> <frame src="right.jsp" name="right" /> </frameset> </frameset> </html>
Filter內Cookie的設置:服務器
package cn.zzsxt.lee.web.filter; 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.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @description 編碼過濾器 * @author Seven Lee * @date 2017年7月28日下午4:48:59 * */ public class GlobalFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 若是是設置編碼,就必須添加chain.doFilter(); // chain.doFilter(request, response); //放這裏有BUG,登陸的時候第一次不會出現帳號密碼,刷新一次纔會出現 // 獲取cookie數組 Cookie[] cookies = request.getCookies(); if (cookies != null) {// 防止空指針 String username = ""; String password = ""; for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].getValue()); if ("username".equals(cookies[i].getName())) { username = cookies[i].getValue(); } if ("password".equals(cookies[i].getName())) { password = cookies[i].getValue(); } } request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password);
chain.doFilter(request, response); //放最後沒BUG } else { for(int i = 0; i < cookies.length; i++){ System.out.println(cookies[i].getValue()); } response.sendRedirect("login.jsp"); return; } } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
Top處登陸成功:cookie
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'top.jsp' starting page</title> <script type="text/javascript"> function trunLogin() { window.top.location.href = "login.jsp"; } </script> </head> <body> <c:choose> <c:when test="${sessionScope.user.username != null }"> //指的是登陸時user對象的屬性 <h1>歡迎:${sessionScope.user.username }</h1> <a href="">註銷</a> </c:when> <c:when test="${sessionScope.username != null }"> //指的是當前Cookie的屬性 <h1>歡迎:${sessionScope.username }</h1> <a href="">註銷</a> </c:when> <c:otherwise> <a href="javascript:void(0);" onclick="trunLogin();">請登陸</a> </c:otherwise> </c:choose> </body> </html>