SpringMVC拦截器:登录拦截器

来源:互联网 发布:中级会计职称题库软件 编辑:程序博客网 时间:2024/05/21 17:26

配置拦截器

<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

@Controllerpublic 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>
原创粉丝点击