Springboot-登錄功能-攔截器-保持登錄狀態
在原先的簡單方法后,完善了功能
前文:https://www.cnblogs.com/djhzzl/p/14117459.html
在原先代碼上添加攔截器和session,保持登錄狀態
攔截器實現:
使用攔截器,保證部分功能需要先登錄,才能訪問
新建攔截器
·自定義攔截器,需要繼承HandlerInterceptorAdapter並重寫preHandle方法
·同時需要設置不攔截頁面靜態資源,否則會加載不到圖片、css等靜態資源
·還需要獲取用戶登錄信息,如果獲取不到,則跳轉到登錄界面。
·代碼如下:
package com.hut.maoyanmovie.interceptor; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * @author HP * @data 2020-12-14 * *新建攔截器 * * 自定義攔截器 */
public class AuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 攔截處理代碼 //靜態資源不被攔截器攔截
String uri = request.getRequestURI(); if (uri.endsWith("js")||uri.endsWith("css")||uri.endsWith("jpg")||uri.endsWith("svg")||uri.endsWith("jpg")||uri.endsWith("png")){ return true ; } HttpSession session = request.getSession(); // 獲取用戶信息,如果沒有用戶信息直接返回提示信息
Object userInfo = session.getAttribute("loginUser"); if (userInfo == null) { request.setAttribute("msg","請先登錄!"); request.getRequestDispatcher("logging").forward(request, response); return false; } else { } return true; } @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 { } }
注冊攔截器
·注冊自己的攔截器並設置攔截的請求路徑
·新建配置類繼承WebMvcConfigurerAdapter類,重寫addInterceptors方法
·既然要增加自己的攔截器,那當然要得到springboot加入攔截器的入口,然后把我們自己寫的攔截器也注冊到springboot中讓其起作用
·需要加入@Configuration注解,在springboot啟動的時候就會該配置類就會被掃描並加載,從而將我們的攔截器注冊進去。這時候的攔截器已經可以正常工作了
package com.hut.maoyanmovie.interceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author HP * @data 2020-12-14 * 注冊攔截器 * 新建配置類繼承WebMvcConfigurerAdapter類,重寫addInterceptors方法 * 既然要增加自己的攔截器,那當然要得到springboot加入攔截器的入口,然后把我們自己寫的攔截器也注冊到springboot中讓其起作用 * 需要加入@Configuration注解,在springboot啟動的時候就會該配置類就會被掃描並加載,從而將我們的攔截器注冊進去。這時候的攔截器已經可以正常工作了 */ @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //注冊自己的攔截器並設置攔截的請求路徑
registry.addInterceptor(new AuthInterceptor()) .addPathPatterns("/interorders/**") //攔截的路徑
.excludePathPatterns(""); //排除的路徑
} }
此時設置,訂單頁面需要的登錄后,才可以訪問。
前端代碼:
<form action="maoyanmovie">
<div class="info">
<h3 th:text="${msg}"></h3>
</div>
<div class="submit">
<input type="submit" value="返回首頁">
</div>
</form>
效果圖:
實現攔截器后,加入session,完成登錄狀態的保持和退出功能
控制器代碼:
session對象主要用於屬性操作和會話管理
package com.hut.maoyanmovie.controller; import com.hut.maoyanmovie.bean.User; import com.hut.maoyanmovie.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; /** * @author HP * @data 2020-12-14 */ @Controller public class IoginController { @Autowired UserService userService; @PostMapping("loginUserByTel") public String login( @RequestParam("user_tel") String user_tel, @RequestParam("user_password") String user_password, Model model, HttpSession session) { User user = userService.loginUserByTel(user_tel, user_password); if (user != null) { model.addAttribute("msg","登錄成功! 歡迎你!"+user.getUser_name()); session.setAttribute("loginUser", user_tel); session.setAttribute("uid",user.getUid()); } else { model.addAttribute("msg", "登錄失敗!用戶名或密碼錯誤!"); } return "logging"; } @RequestMapping("logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/login"; } @GetMapping("logging") public String logging(){ //歡迎頁面
return "logging"; } }
session分析:
public void setAttribute(String name,String value)設定指定名字的屬性的值,並將它添加到session會話范圍內,如果這個屬性是會話范圍內存在,則更改該屬性的值。
public Object getAttribute(String name)在會話范圍內獲取指定名字的屬性的值,返回值類型為object,如果該屬性不存在,則返回null。
public void invalidate(),使session失效。可以立即使當前會話失效,原來會話中存儲的所有對象都不能再被訪問。
此時,當輸入用戶密碼都正確時,將用戶數據通過set'方法放入session中,這樣在后續查詢時,可以通過判斷session是否為空,得知是否登錄
在退出時,通過調用invalidate方法,失效session達到退出的效果