-1
我爲我的JSF項目寫了一個登錄名,並定義了一個小私人部分來測試它。JSF重定向到登錄後請求的頁面
這是我LoginFilter:
@WebFilter("/private/*")
public class LoginFilter implements Filter {
@Inject
private NavigationService navigationService = null;
@Override
public void init(FilterConfig config) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String originalURL = req.getRequestURL().toString();
if(req.getQueryString() != null) {
originalURL += "?" + req.getQueryString();
}
User user = (User) req.getSession().getAttribute("user");
if(user != null) {
chain.doFilter(request, response);
} else {
req.getSession().setAttribute("originalURL", originalURL);
res.sendRedirect(req.getContextPath() + navigationService.toLogin());
}
}
@Override
public void destroy() {}
}
這是我的login服務:
@Named
@SessionScoped
public class LoginService implements Serializable {
private String username = "";
private String password = "";
@Inject
private NavigationService navigationService = null;
@Inject
private DAO dao = null;
private String originalURL = "";
@PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
if(externalContext.getRequestMap().containsKey("originalURL")) {
this.originalURL = (String)externalContext.getRequestMap().get("originalURL");
} else {
this.originalURL = navigationService.externalContextRedirectToIndex();
}
}
public void doLogin() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
User user = dao.findUserByUsername(this.username);
boolean validated = PasswordHasher.validatePassword(this.password, user.getPassword());
if(user != null && validated) {
externalContext.getSessionMap().put("user", user);
vexternalContext.redirect(this.originalURL);
} else {
context.addMessage(null, new FacesMessage("False username or password!"));
}
}
public void doLogout() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath() + navigationService.toLogin());
}
// Getter and Setter
}
如果現在有人正在請求例如 「/private/test.html」 我的登錄 頁出現,用戶必須登錄。之後,如果用戶成功登錄,我想重定向到最初請求的test.html。
現在sessionMap從來沒有一個名爲「originalURL」的鍵,我總是會將 重定向到我的index.html。
順便說一下我的NavigationService提供了兩種方法:
public String redirectToIndex() {
return "/index.html?faces-redirect=true";
}
public String externalContextRedirectToIndex() {
return "/Web-Tschuwwa/index.html?faces-redirect=true";
}
第二種方法,我有登錄 後特意加了重定向,因爲當我用第一種方法我被重定向到的index.html的 我的glassfish docsroot文件夾。這是我不知道爲什麼的另一件事。 Web-Tschuwwa是我的項目的名稱。
登錄後如何重定向到所請求的頁面?