1、前言
一、简单的登陆验证能够经过Session或者Cookie实现。
二、每次登陆的时候都要进数据库校验下帐户名和密码,只是加了cookie 或session验证后;好比登陆页面A,登陆成功后进入页面B,若此时cookie过时,在页面B中新的请求url到页面c,系统会让它回到初始的登陆页面。(相似单点登陆sso(single sign on))。
三、另外,不管基于Session仍是Cookie的登陆验证,都须要对HandlerInteceptor进行配置,增长对URL的拦截过滤机制。css
2、利用Cookie进行登陆验证
一、配置拦截器代码以下:html
public class CookiendSessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.debug("进入拦截器"); Cookie[] cookies = request.getCookies(); if(cookies!=null && cookies.length>0){ for(Cookie cookie:cookies) { log.debug("cookie===for遍历"+cookie.getName()); if (StringUtils.equalsIgnoreCase(cookie.getName(), "isLogin")) { log.debug("有cookie ---isLogin,而且cookie还没过时..."); //遍历cookie若是找到登陆状态则返回true继续执行原来请求url到controller中的方法 return true; } } } log.debug("没有cookie-----cookie时间可能到期,重定向到登陆页面后请从新登陆。。。"); response.sendRedirect("index.html"); //返回false,不执行原来controller的方法 return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
二、在Springboot中拦截的请求不论是配置监听器(定义一个类实现一个接口HttpSessionListener )、过滤器、拦截器,都要配置以下此类实现一个接口中的两个方法。
代码以下:前端
@Configuration public class WebConfig implements WebMvcConfigurer { // 这个方法是用来配置静态资源的,好比html,js,css,等等 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } // 这个方法用来注册拦截器,咱们本身写好的拦截器须要经过这里添加注册才能生效 @Override public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns("/**") 表示拦截全部的请求 //excludePathPatterns("/firstLogin","/zhuce");设置白名单,就是拦截器不拦截。首次输入帐号密码登陆和注册不用拦截! //登陆页面在拦截器配置中配置的是排除路径,能够看到即便放行了,仍是会进入prehandle,可是不会执行任何操做。 registry.addInterceptor(new CookiendSessionInterceptor()).addPathPatterns("/**").excludePathPatterns("/", "/**/login", "/**/*.html", "/**/*.js", "/**/*.css", "/**/*.jpg"); } }
3.前台登陆页面index.html(我把这个html放在静态资源了,也让拦截器放行了此路由url)
前端测试就是一个简单的form表单提交spring
<!--测试cookie和sessionid--> <form action="/login" method="post"> 帐号:<input type="text" name="name1" placeholder="请输入帐号"><br> 密码:<input type="password" name="pass1" placeholder="请输入密码"><br> <input type="submit" value="登陆"> </form>
四、后台控制层Controller业务逻辑:登陆页面index.html,登陆成功后 loginSuccess.html。
在loginSuccess.html中可提交表单进入次页demo.html,也可点击“退出登陆”后台清除没有超时的cookie,而且回到初始登陆页面。数据库
@Controller @Slf4j @RequestMapping(value = "/") public class TestCookieAndSessionController { @Autowired JdbcTemplate jdbcTemplate; /** * 首次登陆,输入帐号和密码,数据库验证无误后,响应返回你设置的cookie。再次输入帐号密码登陆或者首次登陆后再请求下一个页面,就会在请求头中携带cookie, * 前提是cookie没有过时。 * 此url请求方法不论是首次登陆仍是第n次登陆,拦截器都不会拦截。 * 可是每次(首次或者第N次)登陆都要进行,数据库查询验证帐号和密码。 * 作这个目的是若是登陆页面A,登陆成功后进页面B,页面B有连接进页面C,若是cookie超时,从新回到登陆页面A。(相似单点登陆) */ @PostMapping(value = "login") public String test(HttpServletRequest request, HttpServletResponse response, @RequestParam("name1")String name,@RequestParam("pass1")String pass) throws Exception{ try { Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass}); if(result==null || result.size()==0){ log.debug("帐号或者密码不正确或者此人帐号没有注册"); throw new Exception("帐号或者密码不正确或者此人帐号没有注册!"); }else{ log.debug("查询知足条数----"+result); Cookie cookie = new Cookie("isLogin", "success"); cookie.setMaxAge(30); cookie.setPath("/"); response.addCookie(cookie); request.setAttribute("isLogin", name); log.debug("首次登陆,查询数据库用户名和密码无误,登陆成功,设置cookie成功"); return "loginSuccess"; } } catch (DataAccessException e) { e.printStackTrace(); return "error1"; } } /**测试登陆成功后页面loginSuccess ,进入次页demo.html*/ @PostMapping(value = "sub") public String test() throws Exception{ return "demo"; } /** 能进到此方法中,cookie必定没有过时。由于拦截器在前面已经判断力。过时,拦截器重定向到登陆页面。过时退出登陆,清空cookie。*/ @RequestMapping(value = "exit",method = RequestMethod.POST) public String exit(HttpServletRequest request,HttpServletResponse response) throws Exception{ Cookie[] cookies = request.getCookies(); for(Cookie cookie:cookies){ if("isLogin".equalsIgnoreCase(cookie.getName())){ log.debug("退出登陆时,cookie还没过时,清空cookie"); cookie.setMaxAge(0); cookie.setValue(null); cookie.setPath("/"); response.addCookie(cookie); break; } } //重定向到登陆页面 return "redirect:index.html"; } }
五、效果演示:
①在登陆“localhost:8082”输入帐号登陆页面登陆:
浏览器
②拦截器我设置了放行/login,因此请求直接进Controller相应的方法中:
日志信息以下:
下图能够看出,浏览器有些自带的不止一个cookie,这里不要管它们。
tomcat
③在loginSuccess.html,进入次页demo.html。cookie没有过时顺利进入demo.html,而且/sub方法通过拦截器(此请求请求头中携带cookie)。
过时的话直接回到登陆页面(这里不展现了)
④在loginSuccess.html点击“退出登陆”,后台清除我设置的没过时的cookie=isLogin,回到登陆页面。springboot
3、利用Session进行登陆验证
一、修改拦截器配置略微修改下:
Interceptor也略微修改下:仍是上面的preHandle方法中:
cookie
2.核心
前端我就不展现了,就是一个form表单action="login1"
后台代码以下:session
/**利用session进行登陆验证*/ @RequestMapping(value = "login1",method = RequestMethod.POST) public String testSession(HttpServletRequest request, HttpServletResponse response, @RequestParam("name1")String name, @RequestParam("pass1")String pass) throws Exception{ try { Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass}); if(result!=null && result.size()>0){ String requestURI = request.getRequestURI(); log.debug("这次请求的url:{}",requestURI); HttpSession session = request.getSession(); log.debug("session="+session+"session.getId()="+session.getId()+"session.getMaxInactiveInterval()="+session.getMaxInactiveInterval()); session.setAttribute("isLogin1", "true1"); } } catch (DataAccessException e) { e.printStackTrace(); return "error1"; } return "loginSuccess"; } //登出,移除登陆状态并重定向的登陆页 @RequestMapping(value = "/exit1", method = RequestMethod.POST) public String loginOut(HttpServletRequest request) { request.getSession().removeAttribute("isLogin1"); log.debug("进入exit1方法,移除isLogin1"); return "redirect:index.html"; } }
日志以下:能够看见springboot内置的tomcat中sessionid就是请求头中的jsessionid,并且默认时间1800秒(30分钟)。
我也不清楚什么进入拦截器2次,由于我login1设置放行了,确定不会进入拦截器。多是什么静态别的什么资源吧。
session.getId()=F88CF6850CD575DFB3560C3AA7BEC89F==下图的JSESSIONID
//点击退出登陆,请求退出url的请求头仍是携带JSESSIONID,除非浏览器关掉才消失。(该session设置的属性isLogin1移除了,session在不关浏览器状况下或者超过默认时间30分钟后,session才会自动清除!)
4、完结
文章若有错误的地方,还请指教一下!
我是码农小伟,谢谢小伙伴观看,给我关注点个赞,谢谢你们!
留学资讯网 http://www.dzdztdz.cn 留学资讯网 http://www.hlblbdf.cn 留学资讯网 http://www.pbvvnnd.cn