一般使用filter过滤用户是否登录,如果用户没有登陆则转向登陆页面,这时候可以使用response.sendRedirect()。
但当在页面上使用了iframe后,发现被重定向的只是父页面中的iframe区域,登陆页面内容显示在该区域中。说明在过滤器中发送重定向请求时,是在iframe页面发送的。
错误的代码如下:
HttpServletRequest req = (HttpServletRequest) request;
User user = (User) req.getSession().getAttribute("user");
if (user == null)
{
((HttpServletResponse) response).sendRedirect("/login/login.jsp");
}
chain.doFilter(request, response);
因为response.sendRedirect()没有target属性,但html页面和js中有,于是,当判断出用户没有访问权限时,我们可以在jsp中使用js来转向到真正的登录页面。
在filter类的doFilter方法中添加如下代码
:
HttpServletRequest req = (HttpServletRequest) request;
User user = (Visitor) req.getSession().getAttribute("user");
if (visitor == null)
{
java.io.PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<script>");
out.println("window.open ('/login/login.jsp','_top')");
out.println("</script>");
out.println("</html>");
}
chain.doFilter(request, response);
但问题来了:我们在开发中如果使用了Struts框架的话,验证就是用一个Interceptor来做,而对应的jsp又是通过struts.xml配置的
根本不能控制response对象;
Interceptor代码:
package ray.interceptors;
import ray.tools.Consts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
private ActionContext context = null;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
this.context = invocation.getInvocationContext();
Object object = context.getSession().get(Consts.USERSESSION);
if(object == null){
return Action.LOGIN;
} else {
return invocation.invoke();
}
}
}
struts.xml
<span style="white-space:pre"> </span><global-results>
<result name="error">/WEB-INF/error/error.jsp</result>
<result name="login" type="dispatcher">/WEB-INF/jsp/login/login.jsp</result>
<result name="input" type="redirectAction">
<param name="actionName">defAction</param>
</result>
</global-results>
我们在login.jsp中使用一个技巧:
login.jsp:
<%@ page language="java" contentType="text/html"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="${applicationScope.basePath}">
<title>Insert title here</title>
</head>
<body>
<!-- 设置中间页,用来处理登陆页面在iframe中显示的情况 -->
<script type="text/javascript">
if(parent){
parent.location.href="index.jsp";
}
</script>
</body>
</html>
这样的话,就可以在struts框架中让iframe中redirect时,改变top窗口的href了。