![](/img/trans.png)
[英]How to restrict a logged in user to access the login page in spring without using spring security?
[英]How to authenticate logged in user when refreshing single page application using AngularJS without “Routing”?
我搜索了很多资源,但没有一个适合我的问题。我正在处理single page application (SPA)
项目,并且希望logged in user
stay logged in
刷新页面时stay logged in
而 无需进行 路由 。
我试图在页面的主controller
中调用session authentication servlet
(此servlet检查会话是否存在),但是它不起作用。
注意:用户log in
或sing up
便会创建会话。 这是SessionAuthServlet.java
:
HttpSession session = request.getSession(true);
User u=(User) session.getAttribute("usersession");
try{
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
if(u != null)
{
out.println("{\"+success+\"}");
out.close();
}
else
{
out.println("{ \"result\": \"fail\"}");
out.close();
}
}catch (IOException e) {
e.printStackTrace();
}
HTML单页应用程序中的MainController
:
appvar.controller('MianController',['$scope','$http','$rootScope',function($scope, $http,$rootScope) {
$rootScope.sessionvalid=function(){
$http.get("http://localhost:8080/MyProject/SessionAuthServlet")
.success(function(response) {
if (response.result=="fail")
{
//***Show the view for not logged user
}
//***Show the view for logged user
}
$rootScope.sessionvalid();
});
}
}]);
有什么想法如何处理吗?
请指导我
谢谢
在页面刷新后,不使用路由就可以保持登录状态。 您将需要以下三件事
服务代码-
app.service('AuthenticationService', function() {
var auth = {
isLogged: false,
email:"",
isAdmin:false
}
return auth;
});
在您的MainController中,一旦用户登录,请设置Service AuthenticationService.isLogged = true和$ window.sessionStorage = userInfo
拦截器代码-
app.service('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
/* Set Authentication.isAuthenticated to true if 200 received */
response: function (response) {
if (response != null && response.status == 200 && $window.sessionStorage.token && !AuthenticationService.isAuthenticated) {
AuthenticationService.isAuthenticated = true;
}
return response || $q.when(response);
}
};
});
并在您的app.config块中添加-
app.config(function($httpProvider){
$httpProvider.interceptors.push(TokenInterceptor);
})
现在,即使页面已被引荐,您的AuthenticationService.isLogged也将保持为true,并且您可以在服务中获取登录的用户信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.