springmv拦截器

(1)在springmvc.xml中配置映射器和适配器

     <!-- 映射器 --> 
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <property name="interceptors">
            <list>
                <bean class="com.csdn.core.web.SpringmvcInterceptor"></bean>
            </list>
        </property>
    </bean>

    <!-- 适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>

(2)实现类SpringmvcInterceptor

public class SpringmvcInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionProvider sessionProvider;

    //方法前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception { 
        User user = (User) sessionProvider.getAttribute(request,Constans.USER_SESSION);
        boolean flag = false;

        if(user != null){
            flag = true;
        }
        request.setAttribute("flag", flag);
        return true;
    }

    //方法后
    public void postHandle(HttpServletRequest request, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
    }

    //页面渲染后
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }


}

(3)jsp页面

      <c:if test="${!flag }">
      <a href="${pageContext.request.contextPath}/user/toLogin.do" target="_top">登录</a>&nbsp;&nbsp;&nbsp;&nbsp;
      <a href="${pageContext.request.contextPath}/user/toRegister.do" target="_top"">注册</a>
      </c:if>
      <c:if test="${flag }">
      <a href="${pageContext.request.contextPath}/user/toLogout.do" target="_top"">退出</a>&nbsp;&nbsp;&nbsp;&nbsp;
      <a href="${pageContext.request.contextPath}/manage/toZhanghaoManage.do" target="_top"">账号</a>
      </c:if>

(4)springmvc拦截器无效
项目中需要加springMVC拦截器,但加上了不起作用,原来是因为在springmvc.xml文件中配置的这个<mvc:annotation-driven/> 配置文件导致的拦截器失效,把这个注释掉,改成原始的包扫描的方式获取controller,就起作用了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值