Mar*_*ada 22 ajax jquery spring-mvc
I am newbie to ajax here and I know somebody would have encountered this problem already. I have a legacy app built on Spring MVC, it has a interceptor(filter) that redirects the user to the login page whenever there is no session.
public class SessionCheckerInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
// check if userInfo exist in session
User user = (User) session.getAttribute("user");
if (user == null) {
response.sendRedirect("login.htm");
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
For non-xmlhttp request, this works fine.. but when I try to use ajax in my application, everything gets weird, it is not able to redirect to the login page correctly. As check the value of the
xhr.status = 200 textStatus = parseError errorThrown = "Invalid JSON -Markup of my HTML Login Page-
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
//code here
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我检查了我的firebug,有一个302 HTTP响应,但我不知道如何捕获响应并将用户重定向到登录页面.这有什么想法吗?谢谢.
thm*_*shd 50
JQuery正在寻找一个json类型的结果,但由于重定向是自动处理的,它将接收生成的login.htm
页面的html源代码.
一个想法是让浏览器知道它应该通过向redirect
结果对象添加变量并在JQuery中检查它来重定向:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
Run Code Online (Sandbox Code Playgroud)
您还可以在响应中添加标头变量,并让浏览器决定重定向的位置.在Java中,不是重定向,而是response.setHeader("REQUIRES_AUTH", "1")
在JQuery中执行成功(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
我的答案深受这个帖子的启发,如果你还有一些问题,不应该留下任何问题.
归档时间: |
|
查看次数: |
105305 次 |
最近记录: |