gpt4 book ai didi

java - JSF 2.0 : How to redirect to the protected page after using HttpServletRequest. 登录

转载 作者:搜寻专家 更新时间:2023-10-31 20:04:35 25 4
gpt4 key购买 nike

我正在尝试将 HttpServletRequest.login 与基于表单的身份验证结合使用。

一切正常(容器告诉登录名/密码是否正确),除了在用户输入登录名后,我不知道如何将用户重定向到他要求的 protected 页面(登录表单是重新显示)。如何做到这一点?

预先感谢您的帮助。

代码:

web.xml:

<login-config>
<auth-method>FORM</auth-method>
<realm-name>security</realm-name>
<form-login-config>
<form-login-page>/faces/loginwithlogin.xhtml</form-login-page>
<form-error-page>/faces/noaut.xhtml</form-error-page>
</form-login-config>
</login-config>

页面登录和login.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Authentication</title>
</h:head>
<h:body>
<h:form>
Login :
<h:inputText value="#{login.login}" required="true" />
<p/>
Mot de passe :
<h:inputSecret value="#{login.password}" required="true" />
<p/>
<h:commandButton value="Connexion" action="#{login.submit}">
<f:ajax execute="@form" render="@form" />
</h:commandButton>
<h:messages />
</h:form>
</h:body>
</html>

更新:如果没有 Ajax,它就无法工作。

支持 bean:

@Named
@SessionScoped
public class Login implements Serializable {
private String login;
private String password;
// getters and setters
...

public void submit() {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest) context.getExternalContext().getRequest();
try {
request.login(login, mdp);
context.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO,
"OK", null));
} catch (ServletException e) {
context.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Bad login", null));
}
}

}

最佳答案

在容器管理的基于表单的身份验证的情况下,登录页面在由 RequestDispatcher#forward() 打开的幕后。因此,原始请求 URI 可用作请求属性,其名称由 RequestDispatcher#FORWARD_REQUEST_URI 标识.请求属性(基本上,请求范围)在 JSF 中可用 ExternalContext#getRequestMap() .

因此,应该这样做:

private String requestedURI;

@PostConstruct
public void init() {
requestedURI = FacesContext.getCurrentInstance().getExternalContext()
.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

if (requestedURI == null) {
requestedURI = "some/default/home.xhtml";
}
}

public void submit() throws IOException {
// ...

try {
request.login(username, password);
externalContext.redirect(requestedURI);
} catch (ServletException e) {
context.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Bad login", null));
}
}

你只需要制作bean @ViewScoped (JSF) 或 @ConversationScoped (CDI) 而不是 @SessionScoped (绝对不是 @RequestScoped ;否则需要对 <f:param><f:viewParam> 使用不同的方法)。

关于java - JSF 2.0 : How to redirect to the protected page after using HttpServletRequest. 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12245749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com