package com.chb.abc.common.Interceptor;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.chb.abc.model.Administer;
import com.chb.abc.model.Enterprises;
import com.chb.abc.service.AuthorityService;
public class CommonInterceptor implements HandlerInterceptor {
private Logger log = Logger.getLogger(CommonInterceptor.class);
public CommonInterceptor() {}
/**
* 在业务处理器处理请求之前被调用
* 如果返回false
* 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
*
* 如果返回true
* 执行下一个拦截器,直到所有的拦截器都执行完毕
* 再执行被拦截的Controller
* 然后进入拦截器链,
* 从最后一个拦截器往回执行所有的postHandle()
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String callbackURL = request.getServletPath(); //获取当前访问的链接
String sessionId = (String)session.getAttribute("administerUserId");//获取sessionId
//后台管理中心的拦截器
if (callbackURL.startsWith("/manage/")) {
// 1. 得到session中的sessionID
// 2. 如果为空,到登录界面
String szUserId = (String) session.getAttribute("administerUserId");
Object lastActiveTimeObject = session
.getAttribute("lastactivetime");
if (szUserId == null || lastActiveTimeObject == null) {
session.invalidate();
//默认session失效后调到企业登录界面,因为以后登录是给用户用的
callbackURL = request.getContextPath() + "/enterprise/login.html";
response.setContentType("text/html");
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
}
// 3. 如果不为空,但登录时间过长,重新登录
long lastActiveTime = (Long) lastActiveTimeObject;// 获取usessionid的最后一次报活时间戳
// 判断报活时间间隔是否超过25分钟
if ((System.currentTimeMillis() - lastActiveTime) > 25 * 60 * 1000) {
//测试用,时间间隔设置为30秒
// if ((System.currentTimeMillis() - lastActiveTime) > 0.5 * 60 * 1000) {
if((Boolean)session.getAttribute("isEnterprise")!=null) {//企业用户
callbackURL = request.getContextPath() + "/enterprise/login.html";
}
else if((Boolean)session.getAttribute("isEnterprise")==null) {//管理员用户
callbackURL = request.getContextPath() + "/manage/login.html";
}
session.invalidate();
response.setContentType("text/html");
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
} else {
// 4. 如果不为空,且登录时间小于25分钟,允许通过
session.setAttribute("lastactivetime",
System.currentTimeMillis());
//校验通过后,还要校验权限
return checkAuthority(request, response, handler);
}
}
//企业用户登录的拦截器
else if (callbackURL.startsWith("/enterprise/")) {
// 1. 得到session中的sessionID
// 2. 如果为空,到企业界面
String szUserId = (String) session.getAttribute("enterpriseUserId");
Object lastActiveTimeObject = session
.getAttribute("lastactivetime");
if (szUserId == null || lastActiveTimeObject == null) {
session.invalidate();
callbackURL = request.getContextPath() + "/enterprise/login.html";
response.setContentType("text/html");
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
}
// 3. 如果不为空,但登录时间过长,重新登录
long lastActiveTime = (Long) lastActiveTimeObject;// 获取usessionid的最后一次报活时间戳
// 判断报活时间间隔是否超过25分钟
if ((System.currentTimeMillis() - lastActiveTime) > 25 * 60 * 1000) {
session.invalidate();
callbackURL = request.getContextPath() + "/enterprise/login.html";
response.setContentType("text/html");
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
} else {
// 4. 如果不为空,且登录时间小于25分钟,允许通过
session.setAttribute("lastactivetime",
System.currentTimeMillis());
//校验通过后,还要校验权限
//return checkAuthority(request, response, handler);
}
}
return true;
}
private boolean checkAuthority(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
/**
* 对权限进行控制
* @author chb
* @time 2015年5月27日9:59:05
*/
if(request.getServletPath().startsWith("/manage/")){
//1. 获取当前用户
Administer administer = (Administer)request.getSession().getAttribute("user");
if(administer == null){ //没有登录用户,返回登录页面
String callbackURL = request.getContextPath() + "/manage/login.html";
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
}
//2. 获取当前用户是否有访问相应URL的权限
if(!hasAuthority(administer, request.getServletPath()))
{
request.setAttribute("returnMsg", "没有相应的权限!");
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
return false;
}
}
else if(request.getServletPath().startsWith("/enterprise/")){
Enterprises enterprise = (Enterprises)request.getSession().getAttribute("user");
if(enterprise == null){ //没有登录用户,返回登录页面
String callbackURL = request.getContextPath() + "/enterprise/login.html";
response.getWriter().println("<script type=\"text/javascript\"> top.location= '"+ callbackURL + "';</script>");
return false;
}
//2. 获取当前用户是否有访问相应URL的权限
if(!hasAuthority(enterprise, request.getServletPath()))
{
request.setAttribute("returnMsg", "没有相应的权限!");
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
return false;
}
}
return true;
}
/**
*
* @Title:hasAuthority
* @Description: 判断一个用户是否有访问某个路径的权限
* @param administer
* @param szRequestPath
* @return
* @throws
*/
private boolean hasAuthority(Administer administer, String szRequestPath) {
if(administer==null){
return false;
}
//1. 获取当前用户的权限
Set<String> authStrings = authorityService.queryAuthUrlsByUserName(administer.getUserName());
for (String szString : authStrings) {
String[] authURLs = szString.split(",");
for (String authURL : authURLs) {
if(szRequestPath.startsWith(authURL.trim())){
return true;
}
}
}
return false;
}
/**
* 对企业用户进行权限验证
* @param enterprise
* @param szRequestPath
* @author lzz
* @time 2015年5月27日10:09:09
* @return
*/
private boolean hasAuthority(Enterprises enterprise, String szRequestPath) {
if(enterprise==null){
return false;
}
//1. 获取当前用户的权限
Set<String> authStrings = authorityService.queryAuthUrlsByUserName(enterprise.getName());
for (String szString : authStrings) {
String[] authURLs = szString.split(",");
for (String authURL : authURLs) {
if(szRequestPath.startsWith(authURL.trim())){
return true;
}
}
}
return false;
}
/**
* 权限服务
*/
@Autowired
AuthorityService authorityService;
//在业务处理器处理请求执行完成后,生成视图之前执行的动作
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// log.info("==============执行顺序: 2、postHandle================");
}
/**
* 在DispatcherServlet完全处理完请求后被调用
* 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// log.info("==============执行顺序: 3、afterCompletion================");
}
}
在springConfig.xml文件中配置拦截器:
<!--基于注解 拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- 需拦截的地址 -->
<!-- 一级目录 -->
<mvc:mapping path="/*.do" />
<mvc:mapping path="/*.jsp" />
<mvc:mapping path="/*.htm*" />
<!-- 二级目录 -->
<mvc:mapping path="/**/*.do" />
<mvc:mapping path="/**/*.jsp" />
<mvc:mapping path="/**/*.htm*" />
<mvc:exclude-mapping path="/manage/login.html" /><!--排除登录页 -->
<mvc:exclude-mapping path="/enterprise/login.html" /><!--排除登录页 -->
<mvc:exclude-mapping path="/manage/login_out.html" /><!--排除退出链接 -->
<mvc:exclude-mapping path="/manage/verifyImage.html" /><!--排除验证码 -->
<mvc:exclude-mapping path="/manage/error.html" /><!--排除错误展示页 -->
<mvc:exclude-mapping path="/manage/sendOutMessage.html" /><!--排除错误展示页 -->
<mvc:exclude-mapping path="/enterprise/sendOutMessage.html"/>
<mvc:exclude-mapping path="/manage/index.html" />
<mvc:exclude-mapping path="/manage/tab4/userInfo/*" /><!-- 排除个人信息页 -->
<mvc:exclude-mapping path="www.baidu.com"/>
<mvc:exclude-mapping path="/enterprise/ReToSSO.html"/>
<mvc:exclude-mapping path="/enterprise/ssologin.html"/>
<mvc:exclude-mapping path="/enterprise/error.html"/>
<!--session或权限拦截器 -->
<bean class="com.cmcc.flow.common.Interceptor.CommonInterceptor">
</bean>
</mvc:interceptor>
</mvc:interceptors>
authority_info表:
role_info表:
role_auth表:角色-权限表:一对多
administer_info表:
admin_role表:用户-角色表,多对一