SpringMVC应用拦截器判断用户是否登录

拦截器定义

实现HandlerInterceptor接口,实现接口方法。

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 stub
  System.out.println("方法前 1");
  //判断用户是否登陆  如果没有登陆  重定向到登陆页面   不放行   如果登陆了  就放行了
  // URL  http://localhost:8080/springmvc-mybatis/login.action
  //URI /login.action
  String 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 stub
  System.out.println("方法后 1");
  
 }
 public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
   throws Exception {
  // TODO Auto-generated method stub
  System.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";
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值