我正在尝试将 HttpServletRequest.login 与基于表单的身份验证一起使用。
一切都很好(容器告诉登录名/密码是否正确),除了用户输入登录名后,我不知道如何将用户重定向到他要求的受保护页面(重新显示登录表单)。怎么做?
在此先感谢您的帮助。
代码:
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>
页面loginwithlogin.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,它就无法工作。
支撑豆:
@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));
}
}
你只需要制作豆子@ViewScoped
(JSF)或@ConversationScoped
(CDI)代替@SessionScoped
(并且绝对不是@RequestScoped
;否则需要使用不同的方法<f:param>
and <f:viewParam>
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)