zoukankan      html  css  js  c++  java
  • springmvc权限拦截器

    配置文件spring-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"    
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"    
        xmlns:context="http://www.springframework.org/schema/context"    
        xmlns:mvc="http://www.springframework.org/schema/mvc"    
        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"> 
        <!-- 注解扫描包 -->
        <context:component-scan base-package="com.web.controller" />  
    	      
        <!-- 开启注解 -->
        <mvc:annotation-driven/>
        
    
     	<mvc:view-controller path="/" view-name="redirect:/user/logUI" /> 
    <!-- 	<mvc:view-controller path="/" view-name="redirect:/home/index" /> -->
        <!-- 静态资源访问 -->
        <mvc:resources location="/FlatUI/" mapping="/FlatUI/**"/>
        <mvc:resources location="/PAS_V1/" mapping="/FlatUI/**"/>
        <mvc:resources location="/img/" mapping="/img/**"/>
        <mvc:resources location="/js/" mapping="/js/**"/>
        <mvc:resources location="/css/" mapping="/css/**"/>
        <mvc:resources location="/script/" mapping="/script/**"/>
        <mvc:resources location="/style/" mapping="/style/**"/>
       
        	
        <!-- ViewResolver 视图解析器 --> 
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/> 
            <property name="suffix" value=".jsp"/> 
        </bean>
        <!-- 上传文件 -->
         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
              <property name="defaultEncoding"  value="UTF-8"/> 
              <property name="maxUploadSize"    value="1048576000"/> 
              <property name="maxInMemorySize"  value="40960"/> 
        </bean>    
         
        
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**" />
                <bean class="com.web.controller.util.CommonInterceptor" />
            </mvc:interceptor>
        </mvc:interceptors>
    	<!-- json转换器 -->
    	<!--<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
    		<property name="supportedMediaTypes" value="application/json" />
    	</bean> -->
    
         
    </beans>
    

    拦截器源码

    package com.web.controller.util;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.web.controller.entity.User;
    
    public class CommonInterceptor implements HandlerInterceptor {
    	private Log log = LogFactory.getLog(this.getClass());
    	@Override
    	public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
    	}
    
    	@Override
    	public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler, ModelAndView modelAndView) throws Exception {
    		log.info("==============执行顺序: 2、postHandle================");   
    	}
    
    	@Override
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    		log.info("==============执行顺序: 1、preHandle================");   
            String requestUri = request.getRequestURI();  
            String contextPath = request.getContextPath();  
            String url = requestUri.substring(contextPath.length());  
            
            log.info("requestUri:"+requestUri);    
            log.info("contextPath:"+contextPath);    
            log.info("url:"+url);    
            //System.out.println(">>>: " + url);
            // 判断路径是登出还是登录验证,是这两者之一的话执行Controller中定义的方法
            if(url.startsWith("/user/logUI") || url.endsWith("/user/logout")) {
                return true;
            }
            
            // 进入登录页面,判断session中是否有key,有的话重定向到首页,否则进入登录界面
            if(url.startsWith("/user/login/")) {        	
                if(request.getSession() != null && request.getSession().getAttribute("usersession") != null) {
                	return true;  
                } 
                else {   
                	response.sendRedirect("/portal/user/logUI");
                	return false;
                }
            }   
            return true;
    	}
    }
    

    usercontroller中的login代码

    下面对用户名和密码是否为空的判断非常重要, 如果是用户已登录状态, 会造成空指针异常

    @RequestMapping("/login")
    	public String login(String loginName, String password, HttpSession session,HttpServletRequest request){
    		//session.invalidate();
    		User user = null;
    		if(loginName!=null&&password!=null){
    		    user = userService.findByLoginNameAndPassword(loginName, password);}
    		
    		if(user == null){
    			request.setAttribute("loginError", "用户名或者密码错误");			
    			return "/userController/loginUI";
    		}
    		else{
    			session.setAttribute("usersession", user);
    		}
    		return "/homeController/index";
    	}
    
  • 相关阅读:
    AOP面向切面编程相关核心概念
    什么是AOP?
    vue-koa-mongodb管理系统
    js算法(个人整理_彦超)
    前端面试基础总结(个人整理_彦超)
    HTTP 知识点总结(个人整理_彦超)
    前端手写代码整理(个人整理_彦超)
    小程序框架
    nvm 的安装与使用
    three.js 火焰效果
  • 原文地址:https://www.cnblogs.com/wujixing/p/5910062.html
Copyright © 2011-2022 走看看