前端使用angular js、后台使用java做用户的登录控制。当用户未登录时自动跳转到登录页面。
用户登录成功添加session:
HttpSession session=request.getSession();
UserToken usertoken=new UserToken();
usertoken.setNickname((String)map.get("nickname"));
...
usertoken.setUsername((String)map.get("username"));
/*
* 设置session
*/
session.setAttribute("userToken", usertoken);
//超时时间20分钟
session.setMaxInactiveInterval(60*20);
拦截器配置文件代码
applicationContext.xml
<!-- 登录拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截全部地址 -->
<mvc:mapping path="/**" />
<!-- 登录拦截类 -->
<bean id="loginInterceptor"
class="com.beicheng.user.interceptor.LoginInterceptor">
</bean>
</mvc:interceptor>
</mvc:interceptors>
Spirng 拦截器控制类代码
试过在preHandle中使用response.sendRedirect(request.getContextPath()
+”auth/login.html”)做自动跳转没成功,后来直接修改返回的状态码,在前端进行拦截处理
public class LoginInterceptor implements HandlerInterceptor {
//日志
private static Log logger=LogFactory.getLog(LoginInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handle) throws Exception {
//创建session
HttpSession session =request.getSession();
//无需登录,允许访问的地址
String[] allowUrls =new String[]{"/logininfo","/login"};
//获取请求地址
String url =request.getRequestURL().toString();
//获得session中的用户
//userToken是自定义的类,当用户登录成功后向session中添加的
UserToken user =(UserToken) session.getAttribute("userToken");
for (String strUrl : allowUrls) {
if(url.contains(strUrl))
{
return true;
}
}
if(user ==null)
{
//状态码 401 表示用户未登录
response.setStatus(401);
return false;
}
return true;
}
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
angular js拦截器代码
//登录拦截
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
})
app.factory('AuthInterceptor', function ($rootScope, $q,$location) {
return {
requestError:function(request){
return $q.reject(response);
},
responseError:function (response) {
console.log(response);
if(response.status=='401')
{
alert("登录超时!");
$location.url('/auth/login');
}
return $q.reject(response);
}
};
})