shiro简单搭建+spring多数据源配置

配置文件:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-4.0.xsd
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
						http://www.springframework.org/schema/util 
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">


	<context:component-scan base-package="com.admin.service.*"></context:component-scan>
	
	
	<!--统一的dataSource-->
	<bean id="dynamicDataSource" class="com.admin.system.DynamicDataSource" >
	    <property name="targetDataSources">
	        <map key-type="java.lang.String">
	            <!--通过不同的key决定用哪个dataSource-->
	            <entry value-ref="dataSource" key="dataSource"></entry>
	            <entry value-ref="dataSourceOrcl" key="dataSourceOrcl"></entry>
	        </map>
	    </property>
	    <!--设置默认的dataSource-->
	    <property name="defaultTargetDataSource" ref="dataSource">
	    </property>
	</bean>
	
	<!-- 数据库连接池mysql(后台) -->
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:conf/jdbc.properties" />
	<!-- 数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="maxActive" value="10" />
		<property name="minIdle" value="5" />
	</bean>

	<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据库连接池 -->
		<property name="dataSource" ref="dynamicDataSource" />
		<!-- 加载mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<property name="mapperLocations" value="classpath:com/admin/mapper/*/*.xml"></property>
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.admin.mapper.*" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 数据源 -->
		<property name="dataSource" ref="dynamicDataSource" />
	</bean>
	
	<!-- 配置注解事物 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> 
	
	<!-- 数据库连接池oracle(网站) -->
	<bean id="dataSourceOrcl" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${jdbc.orcl.url}" />
		<property name="username" value="${jdbc.orcl.username}" />
		<property name="password" value="${jdbc.orcl.password}" />
		<property name="driverClassName" value="${jdbc.orcl.driver}" />
		<property name="maxActive" value="10" />
		<property name="minIdle" value="5" />
	</bean>

	
</beans>

springMVC-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"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans.xsd
				        http://www.springframework.org/schema/mvc 
				        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
				        http://www.springframework.org/schema/context 
				        http://www.springframework.org/schema/context/spring-context.xsd
				        http://www.springframework.org/schema/util 
				        http://www.springframework.org/schema/util/spring-util-3.0.xsd">


	<context:component-scan base-package="com.admin.web.*"></context:component-scan>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<util:properties id="conf" location="classpath:conf/conf.properties"></util:properties>

	<bean name=""
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 配置静态资源 -->
	<!-- <mvc:resources location="/css/" mapping="/css/**"/> -->
	<!-- <mvc:resources location="/js/" mapping="/js/**"/> -->
	
	<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8"></property> 
        <!-- 最大上传20*1024*1024=5M -->  
        <property name="maxUploadSize" value="20971520"></property>  
   </bean>  
   
    <!-- 启用shrio 控制器授权注解拦截方式 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!-- AOP式方法级权限检查  -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
          <property name="proxyTargetClass" value="true"/>
    </bean>
    
    <!-- 拦截器配置 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**"></mvc:mapping>
 			<mvc:exclude-mapping path="/login.do"/>		
			<bean class="com.admin.system.SecurityInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>
    
</beans>

applicationContext-shiro.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:aop="http://www.springframework.org/schema/aop"  
       xmlns:tx="http://www.springframework.org/schema/tx"  
       xmlns:context="http://www.springframework.org/schema/context"  
       xsi:schemaLocation="  
				http://www.springframework.org/schema/beans 
				http://www.springframework.org/schema/beans/spring-beans.xsd  
				http://www.springframework.org/schema/tx 
				http://www.springframework.org/schema/tx/spring-tx.xsd  
				http://www.springframework.org/schema/aop 
				http://www.springframework.org/schema/aop/spring-aop.xsd  
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context.xsd">  
  	
  	<!-- AdminShiro -->
  	<bean id="adminShiro" class="com.admin.system.AdminShiro"></bean>
  	
    <!-- 配置权限管理器 -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
        <!--  AdminShiro -->  
        <property name="realm" ref="adminShiro"/>    
        <!-- 缓存管理器 -->  
        <property name="cacheManager" ref="cacheManager"/>    
    </bean>  
      
    <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">   
        <!-- 调用权限管理器 -->   
        <property name="securityManager" ref="securityManager"/>   
        <!-- 配置登录请求地址 -->   
        <property name="loginUrl" value="/login.jsp"/>    
        <!-- 配置在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->  
        <property name="successUrl" value="/index.do"/>    
        <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->  
        <property name="unauthorizedUrl" value="/403.jsp"/>    
        <!-- 权限配置 -->  
        <property name="filterChainDefinitions">    
            <value>    
                <!-- anon表示此地址不需要任何权限即可访问 --> 
                 /login.do=anon 
                <!-- /assets/**=anon -->  
                <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->  
                <!-- /user=perms[user:query]  --> 
                <!-- roles[manager]表示访问此连接需要用户的角色为manager -->  
               
                <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->    
				<!--   /**=user   -->
            </value>    
        </property>    
    </bean>  
      
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />   
      
</beans>  

Java代码:

JsonUtil.java

package com.admin.util;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json工具类
 * 
 * @author 
 * @date 2017年5月28日
 */
public class JsonUtil {

	private static final ObjectMapper json = new ObjectMapper()
			.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

	public static String toString(Object obj) throws JsonProcessingException {

		return obj == null ? "" : json.writeValueAsString(obj);

	}

	public static <T> T toObj(String str, Class<T> valueType)
			throws JsonParseException, JsonMappingException, IOException {
		if (StringUtils.isEmpty(str)) {
			return null;
		}
		return json.readValue(str, valueType);
	}

	public static <T> T toList(String str, TypeReference<T> valueTypeRef)
			throws JsonParseException, JsonMappingException, IOException {
		if (StringUtils.isEmpty(str) || null == valueTypeRef) {
			return null;
		}
		return json.readValue(str, valueTypeRef);
	}
	
	
	
}

Print4JUtils.java

package com.admin.util;

import org.apache.commons.lang3.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class Print4JUtils {
	/**
	 * 获取汉字串拼音首字母,英文字符不变
	 * 
	 * @param chinese
	 *            汉字串
	 * @return 汉语拼音首字母
	 */
	public static String getFirstSpell(String chinese) {
		if (StringUtils.isEmpty(chinese)) {
			return null;
		}
		StringBuffer pybf = new StringBuffer();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > 128) {
				try {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
					if (temp != null) {
						pybf.append(temp[0].charAt(0));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(arr[i]);
			}
		}
		return pybf.toString().replaceAll("\\W", "").trim();
	}

	/**
	 * 获取汉字串拼音,英文字符不变
	 * 
	 * @param chinese
	 *            汉字串
	 * @return 汉语拼音
	 */
	public static String getFullSpell(String chinese) {
		if (StringUtils.isEmpty(chinese)) {
			return null;
		}
		StringBuffer pybf = new StringBuffer();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > 128) {
				try {
					pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(arr[i]);
			}
		}
		return pybf.toString();
	}
}

PropertiesUtil.java

package com.admin.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

/**
 * 从配置文件获取
 * 
 * @author 
 * @date 2017年5月27日
 */
public class PropertiesUtil {

	/**
	 * 根据key获取properties配置value
	 * 
	 * @param key
	 * @param fileName
	 *            ("/conf/conf.properties")
	 * @return
	 * @author 
	 * @date 2017年5月27日
	 */
	public static String getValue(String key, String fileName) {
		String value = null;
		if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(fileName)) {
			Properties properties = getProperties(fileName);
			value = properties.getProperty(key);
		}

		return value;
	}
	
	public static Properties getProperties(String fileName) {
		if (StringUtils.isNotEmpty(fileName)) {

			Properties properties = new Properties();
			try {
				// 加载文件
				properties.load(PropertiesUtil.class.getResourceAsStream(fileName));
				return properties;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(getValue("ftp.username", "/conf/conf.properties"));

	}

}

WebUtils.java

package com.admin.util;

import javax.servlet.http.HttpServletRequest;

public class WebUtils {

	/**
	 * 判断是否是ajax请求
	 * 
	 * @param request
	 * @return
	 * @author 
	 * @date 2017年6月24日
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("x-requested-with");
		if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}
}

StringEscapeEditor.java

package com.admin.util;

import java.beans.PropertyEditorSupport;

import org.springframework.web.util.HtmlUtils;

public class StringEscapeEditor extends PropertyEditorSupport {
    public StringEscapeEditor() {}

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null) {
            setValue(null);
        } else {
            setValue(HtmlUtils.htmlEscape(text));
        }
    }

}

以上是工具类

BaseController.java

package com.admin.system.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import com.admin.pojo.admin.User;
import com.admin.system.CSRFTokenManager;
import com.admin.system.DateEditor;
import com.admin.util.JsonUtil;
import com.admin.util.WebUtils;
import com.admin.vo.AdminResult;

/**
 * 基础 controller
 * 
 * @author 
 * @date 2017年6月23日
 */
public abstract class BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		/**
		 * 自动转换日期类型的字段格式
		 */
		binder.registerCustomEditor(Date.class, new DateEditor());
		/**
		 * 防止XSS攻击
		 */
		// binder.registerCustomEditor(String.class, new StringEscapeEditor());
	}

	/**
	 * 获取当前登录用户对象
	 * 
	 * @return {ShiroUser}
	 */
	public User getShiroUser() {
		return (User) SecurityUtils.getSubject().getPrincipal();
	}

	/**
	 * 获取当前登录用户id
	 * 
	 * @return {Long}
	 */
	public Long getUserId() {
		return this.getShiroUser().getId();
	}

	/**
	 * 获取当前登录用户名
	 * 
	 * @return {String}
	 */
	public String getStaffName() {
		return this.getShiroUser().getUserName();
	}

	/**
	 * redirect跳转
	 * 
	 * @param url
	 *            目标url
	 */
	protected String redirect(String url) {
		return new StringBuilder("redirect:").append(url).toString();
	}

	/**
	 * 设置菜单选中
	 * 
	 * @param request
	 * @author 
	 * @date 2017年6月23日
	 */
	protected void activeMenu(HttpServletRequest request) {
		String menuIds = request.getParameter("mn");
		if (StringUtils.isNotBlank(menuIds)) {
			String[] ids = menuIds.split("-");
			// 菜单选中
			if (ids != null && ids.length > 1) {
				request.setAttribute("menuOpen", ids[1]);
			}
			request.setAttribute("menuActive", ids[0]);

		}
	}

	/**
	 * 权限异常
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author 
	 * @date 2017年6月24日
	 */
	@ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
	public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
		if (WebUtils.isAjaxRequest(request)) {
			// 输出JSON
			writeJson(AdminResult.error("无权限"), response);
			return null;
		} else {
			return "redirect:/403.jsp";
		}
	}

	/**
	 * 输出JSON
	 * 
	 * @param result
	 * @param response
	 * @author 
	 * @date 2017年6月24日
	 */
	protected void writeJson(AdminResult result, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
			out.write(JsonUtil.toString(result));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 防止 CSRF
	 * 
	 * @param request
	 * @return
	 * @author 
	 * @date 2017年6月26日
	 */
	protected boolean checkCSRF(HttpServletRequest request) {
		return CSRFTokenManager.checkTokenFromRequest(request);
	}
}

AdminShiro.java 这是处理Shiro权限业务关键实现类

package com.admin.system;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.admin.pojo.admin.Menu;
import com.admin.pojo.admin.User;
import com.admin.service.admin.MenuService;
import com.admin.service.admin.UserService;

/**
 * 
 * @author 
 * @date 2017年5月30日
 */
public class AdminShiro extends AuthorizingRealm {

	private final Logger logger = LoggerFactory.getLogger(AdminShiro.class);

	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;

	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

		// 获取用户
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		// 到数据库查是否有此对象
		try {
			if (user != null) {
				// 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				// 用户的角色集合
				Set<String> roleSet = new HashSet<String>();
				roleSet.add(user.getRoleName()); // 角色
				info.setRoles(roleSet);
				// 用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要
				Set<String> permissions = new HashSet<>();
				List<Menu> menus = menuService.queryByRoleId(user.getRoleId());
				for (Menu menu : menus) {
					if (StringUtils.isNotEmpty(menu.getUrl())) {
						permissions.add(menu.getUrl());
					}
				}
				info.addStringPermissions(permissions); // 权限
				return info;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("权限认证错误", e);
		}

		return null;
	}

	/**
	 * 登陆认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// UsernamePasswordToken对象用来存放提交的登录信息
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		// 查出是否有此用户
		User user;
		try {
			user = userService.findByName(token.getUsername());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("根据用户名查询用户信息错误", e);
			throw new AuthenticationException("根据用户名查询用户信息错误", e);
		}
		if (user != null) {
			// 若存在,将此用户存放到登录认证info中
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
		return null;
	}

}

SecurityInterceptor.java 这事出ajax请求

package com.admin.system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.admin.pojo.admin.User;
import com.admin.util.AdminConstant;
import com.admin.util.JsonUtil;
import com.admin.util.WebUtils;
import com.admin.vo.AdminResult;

public class SecurityInterceptor extends HandlerInterceptorAdapter {

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

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

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

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(AdminConstant.SESSION_USER);
		// session 用户是否登陆
		if (null == user) {
			if (WebUtils.isAjaxRequest(request)) {
				// 输出JSON
				PrintWriter out = null;
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json; charset=utf-8");
					out = response.getWriter();
					out.write(JsonUtil.toString(AdminResult.error("请重新登录")));
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (out != null) {
						out.close();
					}
				}

			} else {
				response.sendRedirect(request.getContextPath() + "/login.jsp");
			}
			return false;
		}

		return true;

	}

}

DynamicDataSource.java动态数据源AbstractRoutingDataSource实现类

package com.admin.system;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
	protected Object determineCurrentLookupKey() {
		// TODO Auto-generated method stub
		return DataSourceControl.getCustomerType();
	}

}

DataSourceControl.java

package com.admin.system;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * 数据库切换控制
 * 
 * @author 
 *
 */
public class DataSourceControl {

	public static final String DATASOURCE_MYSQL = "dataSource";
	public static final String DATASOURCE_ORACLE = "dataSourceOrcl";

	// 用ThreadLocal来设置当前线程使用哪个dataSource
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	public static void setCustomerType(String customerType) {
		contextHolder.set(customerType);
	}

	public static String getCustomerType() {
		String dataSource = contextHolder.get();
		if (StringUtils.isEmpty(dataSource)) {
			return DATASOURCE_MYSQL;
		} else {
			return dataSource;
		}
	}

	public static void clearCustomerType() {
		contextHolder.remove();
	}
}

CSRF攻击防御,请求头中携带session中生产的随机数uuid,Controller中调用BaseController中checkCSRF(request)方法

	$.ajax({
			  		 type: 'POST',
			  		 url: url ,
			  		 dataType: "json", 
			  		 data: obj, //data: {key:value}, 
			  		 headers : {'CSRFToken':'${CSRFToken}'},
			  		 //请求成功的回调函数
			  		 success: function(data){
			  			if(data.status==200){
			  				layer.msg('删除成功',{time:2000});
			  				setTimeout(function(){
				  				location.reload();
			  				}, 500)
		 	  			}else{
		 	  				layer.msg(data.msg,{time:2000});
		 	  			}
			  		}
			  	});
package com.admin.system;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class CSRFTokenManager {

	static final String CSRF_PARAM_NAME = "CSRFToken";

	public static final String CSRF_TOKEN_SESSION_NAME = "CSRFTokenSession";

	/**
	 * 设置CSRFToken
	 * 
	 * @param session
	 * @author 
	 * @date 2017年6月26日
	 */
	public static void setTokenForSession(HttpSession session) {
		synchronized (session) {
			String token = (String) session.getAttribute(CSRF_TOKEN_SESSION_NAME);
			if (null == token) {
				token = UUID.randomUUID().toString();
				session.setAttribute(CSRF_TOKEN_SESSION_NAME, token);
			}
		}
	}

	/**
	 * 判断参数获取CSRFToken
	 * 
	 * @param request
	 * @return
	 * @author 
	 * @date 2017年6月26日
	 */
	public static boolean checkTokenFromRequest(HttpServletRequest request) {
		return request.getSession().getAttribute(CSRF_TOKEN_SESSION_NAME).equals(request.getHeader(CSRF_PARAM_NAME));
	}

	private CSRFTokenManager() {
	};

}

DateEditor.java处理请求参数为时间类型

package com.admin.system;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class DateEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		if (StringUtils.isBlank(text)) {
			return;
		}
		try {
			date = format.parse(text);
		} catch (ParseException e) {
			format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				date = format.parse(text);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
		setValue(date);
	}
}

JSP页面权限显示:1.控制页面权限按钮展示 2.控制直接输入url越权访问

<shiro:hasPermission name="inStorage/doCheck.do">
	<button type="button" onclick="doCheck();">审核</button>
</shiro:hasPermission>
@RequiresPermissions("inStorage/doCheck.do")
@RequestMapping(value = "doCheck", method = RequestMethod.POST)
@ResponseBody
public AdminResult doCheck(HttpServletRequest request, InStorage inStorage) {
}

 

转载于:https://my.oschina.net/ludd79806329/blog/1186424

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值