當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringMVC应用拦截器判断用户是否登录
生活随笔
收集整理的這篇文章主要介紹了
SpringMVC应用拦截器判断用户是否登录
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
攔截器定義
實現(xiàn)HandlerInterceptor接口,實現(xiàn)接口方法。
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;public class Interceptor1 implements HandlerInterceptor{public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {// TODO Auto-generated method stubSystem.out.println("方法前 1");//判斷用戶是否登陸? 如果沒有登陸? 重定向到登陸頁面?? 不放行?? 如果登陸了? 就放行了// URL? http://localhost:8080/springmvc-mybatis/login.action//URI /login.actionString requestURI = request.getRequestURI();if(!requestURI.contains("/login")){String username = (String) request.getSession().getAttribute("USER_SESSION");if(null == username){response.sendRedirect(request.getContextPath() + "/login.action");return false;}}return true;}public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)throws Exception {// TODO Auto-generated method stubSystem.out.println("方法后 1");}public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {// TODO Auto-generated method stubSystem.out.println("頁面渲染后 1");}}攔截器配置
在springmvc.xml中配置攔截器
?<!-- SPringmvc的攔截器 --><mvc:interceptors><!-- 多個攔截器 --><mvc:interceptor><mvc:mapping path="/**"/><!-- 自定義的攔截器類 --><bean class="com.itheima.springmvc.interceptor.Interceptor1"/></mvc:interceptor></mvc:interceptors>編寫登錄jsp
<title>登錄</title></head> <body> <form action="${pageContext.request.contextPath }/login.action" method="post">用戶名:<input type="text" name="username" placeholder="輸入用戶名"><input type="submit" value="提交"> </form> </body>編寫用戶登錄Controller
//去登陸的頁面@RequestMapping(value = "/login.action",method = RequestMethod.GET)public String login(){return "login";}@RequestMapping(value = "/login.action",method = RequestMethod.POST)public String login(String username,HttpSession httpSession){httpSession.setAttribute("USER_SESSION", username);return "redirect:/item/itemlist.action";}?
總結(jié)
以上是生活随笔為你收集整理的SpringMVC应用拦截器判断用户是否登录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Xcode更改ios app图标
- 下一篇: SpringMVC的常用注解