SpringMVC拦截器:登录拦截器

配置拦截器

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/><!-- 对所有uri进行拦截 -->
        <mvc:exclude-mapping path="/login" /><!-- 排除拦截的uri:进入登录页面的uri -->
        <mvc:exclude-mapping path="/dologin" /><!-- 排除拦截的uri:处理登录的uri -->
        <bean class="interceptor.LoginInterceptor" /><!-- 登录拦截器类 -->
    </mvc:interceptor>
</mvc:interceptors>

版本导致的问题

注意:把spring-mvc-3.1.xsd改成spring-mvc-3.2.xsd,不然会启动会报错

cvc-complex-type.2.4.a: Invalid content was found starting with element 'mvc:exclude-mapping'. One of '{"http://www.springframework.org/schema/mvc":mapping, "http://www.springframework.org/schema/beans":bean, "http://www.springframework.org/schema/beans":ref}' is expected.

拦截器LoginInterceptor.java

/**
 * 登录拦截器,继承自HandlerInterceptor,实现preHandle方法
 * 
 * 只要访问的页面时还用户未登录,则一律重定向至登录页面。(我们已经在配置中排除了对登录的拦截)
 * 已登录过的页面则通过
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user");
        System.out.println("RequestURI = " + request.getRequestURI());;
        if(user == null){
            System.out.println("have not logged in yet...");
            response.sendRedirect(request.getContextPath() + "/login?url="+request.getRequestURI());
        }else{
            System.out.println("logged in...");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

}

处理器LoginController.java

@Controller
public class LoginController{

    @RequestMapping("/login")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        req.setAttribute("url", req.getParameter("url"));
        return "login";
    }

    @RequestMapping("/dologin")
    public void dologin(String username, HttpServletRequest req, HttpServletResponse resp) throws JsonGenerationException, JsonMappingException, IOException {
        req.getSession().setAttribute("user", "thisUser");
        JSONObject json = new JSONObject();
        json.accumulate("flag", true);
        resp.getWriter().print(json.toString());
    }

}

登录页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>sign in</title>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<a href="javascript:;" onclick="ajaxLogin()">login in</a>
<script type="text/javascript">
    function ajaxLogin(){
        $.ajax({
            url : 'dologin',
            type : 'post',
            dataType : 'json',
            success : function(data) {
                console.log(data.flag);
                if(data.flag == true){
                    if('${url}' != ''){
                        window.location.href='${url}';
                    }else{
                        window.location.href="your default path";
                    }
                }else{
                    console.log('login failed');
                }

            }
        });
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值