如果用户已经登录,如何将用户重定向到主页。我使用Filter类登录页面,但它无法正常工作。我的代码是:
@WebFilter(filterName = "loginFilter",
urlPatterns ={"/login.xhtml"})
public class LoginFilter implements Filter{
private FilterConfig filterconfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterconfig = filterconfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest =(HttpServletRequest) request;
HttpServletResponse httpresponse =(HttpServletResponse) response;
try{
if(httprequest.getUserPrincipal() != null){
System.out.printf("User authenticated with " + httprequest.getRemoteUser() + " username conected.");
httprequest.getRequestDispatcher("/home.xhtml").forward(request, response);
} else{
chain.doFilter(request, response);
}
}catch(Exception){
//do something
}
}
@Override
public void destroy() {
System.out.print("Existing from loginFilter");
}
}
这是我的问题:用户登录到网络并使用浏览器的后退按钮返回登录页面而无需注销,再次输入用户名密码然后按登录按钮。然后它抛出异常 IndexOutOfBoundsException异常。我只需要检查用户何时使用链接或浏览器的后退按钮导航到登录页面,然后重定向到主页。有什么建议吗?
答案 0 :(得分:3)
告诉浏览器不要缓存登录页面。在您将回复转换为httpresponse
之后,请直接将以下行添加到过滤器。
httpresponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
httpresponse.setHeader("Pragma", "no-cache"); // HTTP 1.0.
httpresponse.setDateHeader("Expires", 0); // Proxies.
否则,浏览器会从缓存后退按钮给出页面,而不是发送应该触发过滤器的服务器的完整请求。
答案 1 :(得分:0)
在我看来,使用BalusC的技巧比过滤器更好:
<f:view>
<f:metadata>
<f:viewAction action="#{login.checkLogin()}"/>
</f:metadata>
...
</f:view>
public String checkLogin() {
if (getRequest().getRemoteUser() != null) {
getResponse().setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
getResponse().setHeader("Pragma", "no-cache"); // HTTP 1.0.
getResponse().setDateHeader("Expires", 0); // Proxies.
return "Home";
}
return null;
}
我不认为您应该像这样打断过滤器链,因为链中可能还有另一个您不知道的重要过滤器。