前后台分离使用cookie判断用户状态以及传递参数
生活随笔
收集整理的這篇文章主要介紹了
前后台分离使用cookie判断用户状态以及传递参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
- 在之前學習servlet的時候,當時做的小網站需要登陸并且判斷信息,當時使用session傳值,使用fitter過濾判斷,當時感覺哇,session咋這么好用,cookie是啥玩意,還不方便。
- 后來在學習ssm做項目遇到需要登陸的狀態,在html無法使用session,只能學習cookie了,對于cookie只是在爬蟲中用過,為了爬去登陸后的頁面,看來那些網站都是用cookie保持會話的呢。
- 用了cookie發現cookie也很方便。但是js操作cookie很麻煩用jquery就很簡單。
前端需要引入
.添加一個"會話cookie"
$.cookie('cookie’name, ‘cookievalue’);
讀取cookie
$.cookie(‘the_cookie’);
5.刪除cookie
$.cookie(‘cookiename’, null); //通過傳遞null作為cookie的值即可
還有更多操作請百度。
后端操作demo
@RequestMapping(value="/admin") public String admin(HttpServletRequest request, HttpServletResponse respose){if(request.getMethod().equals("GET")){Cookie[] cookies = request.getCookies();if(cookies!=null &&cookies.length>0)//判斷是否已經登陸已經登陸{for (Cookie cookie : cookies) {if(cookie.getName().equals("userid")&&cookie.getValue()!=null){List<Map> map = foodmapper.getadmin(cookie.getValue());if(map.size()>0)return "admin";else{return "login";}}}}return "login";}else{String username = request.getParameter("username");List<Map> map = foodmapper.getadmin(username);if(map.size()==0){return "login";}String password = (String) map.get(0).get("password");System.out.println(password);if (username.equals(map.get(0).get("username"))&&password.equals(request.getParameter("password"))) {Cookie cookie = new Cookie("userid", username);respose.addCookie(cookie);return "admin";}elsereturn "default";}}對比起來還是客戶端的cookie好用,他就像map一條記錄,而后臺的更像是cookie數組。需要遍歷。
- 如果對后端、爬蟲、數據結構算法等感性趣歡迎關注我的個人公眾號交流:bigsai
總結
以上是生活随笔為你收集整理的前后台分离使用cookie判断用户状态以及传递参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Springmvc文件上传(servle
- 下一篇: 快速幂模板(java)