Spring MVC使用拦截器实现权限控制

1、首先准备对应的架包


Spring MVC使用拦截器实现权限控制

2、看看项目的架构

Spring MVC使用拦截器实现权限控制

3、基本的web.xml文件

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>shiro</display-name>
 
    <!-- 加载springmvc -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <!-- 以.htm结尾的都被mvc拦截 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
     
    <!-- 启动spring 加载   需要加载其他的spring时 需启动该监听器
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     -->
</web-app>

4、配置classpath下的mvc.xml文件

<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd 
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <mvc:annotation-driven>
    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.cat.spring.controller">
 
    <!--  配置mvc的拦截器 可以配置多个 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--  需要被拦截的路径 -->
            <mvc:mapping path="/member/**">
            <!-- 拦截处理的interceptor -->
            <bean class="com.cat.interceptor.MemberInterceptor">
        </bean></mvc:mapping></mvc:interceptor>
    </mvc:interceptors>
 
    <!-- mvc返回页面的配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
        <!-- 模板路径为WEB-INF/pages/ -->
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <!-- 视图模板后缀为.JSP -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</context:component-scan></mvc:annotation-driven></beans>

5、接着就要配置拦截器了MemberInterceptor.java

/**
 * 
 */
package com.cat.interceptor;
 
import java.net.URLEncoder;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author chenlf
 * 
 *         2014-3-25
 */
public class MemberInterceptor implements HandlerInterceptor {
 
    public final static String SEESION_MEMBER = "seesion_member";
 
    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception arg3) throws Exception {
        // TODO Auto-generated method stub
 
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
 
    }
 
    /*
     * (non-Javadoc)
     * 拦截mvc.xml配置的/member/**路径的请求
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        //请求的路径
        String contextPath=request.getContextPath();
        String  url=request.getServletPath().toString();
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute(SEESION_MEMBER);
        //这里可以根据session的用户来判断角色的权限,根据权限来重定向不同的页面,简单起见,这里只是做了一个重定向
        if (StringUtils.isEmpty(user)) {
            //被拦截,重定向到login界面
            response.sendRedirect(contextPath+"/login.htm?redirectURL="
                    + URLEncoder.encode(url));
            return false;
        }
        return true;
    }
 
}

这样拦截器的核心就配置完了,接下来就是一些登陆的处理操作

6、LoginController.java文件

package com.cat.spring.controller;
 
import java.net.URLDecoder;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import com.cat.interceptor.MemberInterceptor;
 
/**
 * @author chenlf
 * 
 *         2014-3-24
 */
@Controller
public class LoginController {
 
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(String redirectURL, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        //把拦截前路径存下来,以便登入成功可以直接请求到登录前的页面
        view.addObject("redirectURL", redirectURL);
        view.setViewName("/login");
        return view;
    }
 
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(String username, String password, String redirectURL,
            HttpServletRequest request) {
        //模拟登陆成功 用户admin 密码admin的用户
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)
                && username.equals("admin") && password.equals("admin")) {
            //当登陆成功是,将用户信息存放到session中去
            HttpSession session = request.getSession();
            session.setAttribute(MemberInterceptor.SEESION_MEMBER, "admin");
            if (StringUtils.isNotBlank(redirectURL)) {
                return "redirect:" + URLDecoder.decode(redirectURL);
            }
            return "redirect:/member/index.htm";
        } else {
            if (StringUtils.isNotBlank(redirectURL)) {
                return "redirect:/login.htm?" + URLDecoder.decode(redirectURL);
            }
            return "redirect:/login.htm";
        }
    }

7、下面就是login.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="utf-8"%>

8、到这里看看效果吧

a、当非登陆状态的时候,请求localhost:8010/demo-mvc/member/list.htm时,被拦截拦截,重定向到login页面,并携带了当前的这个路径(/member/list.htm)作为参数传到页面

Spring MVC使用拦截器实现权限控制

b、输入正确的用户名admin 密码admin后登陆,会跳转到拦截前的页面

Spring MVC使用拦截器实现权限控制

c、当登陆完成后,输入地址为http://localhost:8010/demo-mvc/member/index.htm,session中记录着当前用户的信息,不需要重新登陆了

Spring MVC使用拦截器实现权限控制


上一篇:eclipse 无法导入项目


下一篇:对比Xcode Debug Memory Graph和FBMemoryProfiler