未登录不允许访问项目文件夹内的页面那如何判断是否登录呢?
下面向大家详细介绍spring mvc Session拦截器的使用本文以登录为例未登录无权限访问项目内页面session为空时返回项目首页
代码如下
[html]
package comsundearsundearemminterceptor;
import comsundearsundearemmmodelUser;
import javautilloggingLevel;
import javautilloggingLogger;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgspringframeworkwebservletHandlerInterceptor;
import orgspringframeworkwebservletModelAndView;
/**
*
* @author yh
*/
public class SessionInterceptor implements HandlerInterceptor {
private Logger logger = LoggergetLogger(SessionInterceptorclassgetName());
@Override
public boolean preHandle(HttpServletRequest hsr HttpServletResponse hsr Object o) throws Exception {
User user=(User) hsrgetSession()getAttribute(LoginUser);
if(user==null){
loggerlog(LevelINFO user not login);
hsrsendRedirect(/SundearEmm);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest hsr HttpServletResponse hsr Object o ModelAndView mav) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest hsr HttpServletResponse hsr Object o Exception excptn) throws Exception {
}
}
package comsundearsundearemminterceptor;
import comsundearsundearemmmodelUser;
import javautilloggingLevel;
import javautilloggingLogger;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgspringframeworkwebservletHandlerInterceptor;
import orgspringframeworkwebservletModelAndView;
/**
*
* @author yh
*/
public class SessionInterceptor implements HandlerInterceptor {
private Logger logger = LoggergetLogger(SessionInterceptorclassgetName());
@Override
public boolean preHandle(HttpServletRequest hsr HttpServletResponse hsr Object o) throws Exception {
User user=(User) hsrgetSession()getAttribute(LoginUser);
if(user==null){
loggerlog(LevelINFO user not login);
hsrsendRedirect(/SundearEmm);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest hsr HttpServletResponse hsr Object o ModelAndView mav) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest hsr HttpServletResponse hsr Object o Exception excptn) throws Exception {
}
}
仅这些还不够我们还需要修改spring mvc的配置文件dispatcherservletxml加入拦截器代码如下
[html]
<! interceptors >
<mvc:interceptors >
<mvc:interceptor>
<mvc:mapping path=/group/* />
<mvc:mapping path=/user/*/>
<mvc:mapping path=/subscribe/*/>
<mvc:mapping path=/recipient/*/>
<mvc:mapping path=/mail/*/>
<bean class=comsundearsundearemminterceptorSessionInterceptor></bean>
</mvc:interceptor>
</mvc:interceptors>
<! interceptors >
<mvc:interceptors >
<mvc:interceptor>
<mvc:mapping path=/group/* />
<mvc:mapping path=/user/*/>
<mvc:mapping path=/subscribe/*/>
<mvc:mapping path=/recipient/*/>
<mvc:mapping path=/mail/*/>
<bean class=comsundearsundearemminterceptorSessionInterceptor></bean>
</mvc:interceptor>
</mvc:interceptors>如有访客不明白的可以给我留言我会给大家满意的解决方法……