jsf-2 – 如何在JSF表单中执行Spring Security身份验证

前端之家收集整理的这篇文章主要介绍了jsf-2 – 如何在JSF表单中执行Spring Security身份验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个简单的JSF登录页面,我正在尝试将其与 spring安全性集成.

这是login.xhtml中的表单元素

  1. <h:form>
  2.  
  3. <h:outputLabel value="User Id:" for="userId"/>
  4.  
  5. <h:inputText id="j_username" label="User Id"
  6. required="true" value="#{loginBean.name}" >
  7.  
  8. </h:inputText>
  9.  
  10. <h:outputLabel value="Password: " for ="password"/>
  11.  
  12. <h:inputSecret id="j_password" value="#{loginBean.password}" />
  13.  
  14. <h:commandButton value="Submit" action="#{j_spring_security_check}" />
  15.  
  16. </h:form>

但渲染的html页面有类似下面的内容.看一下表单操作和输入标签名称

表单元素

  1. <form id="j_idt6" name="j_idt6" method="post"
  2. action="/jsfproject2/faces/login.xhtml"
  3. enctype="application/x-www-form-urlencoded">

和输入标签

  1. User Id:</label><input id="j_idt6:j_username" type="text"
  2. name="j_idt6:j_username" />

现在我希望表单操作为/ j_spring_security_check,输入框为’j_username’和j_password

我们怎样才能做到这一点?

解决方法

Spring Security有两种选择.

在JSF表单上使用prependId =“false”

如< h:form>是一个命名容器,它为其子级的id添加了指定的id或自动生成的id,因此Spring Security期望id保持unchainged,只是不要添加id:

  1. <h:form prependId="false">
  2. <h:outputLabel value="User Id: " for="userId" />
  3. <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" />
  4. <h:outputLabel value="Password: " for ="password" />
  5. <h:inputSecret id="j_password" value="#{loginBean.password}" />
  6. <h:commandButton value="Submit" action="#{loginBean.login}" />
  7. </h:form>

请注意,#{j_spring_security_check}是一个错误的操作方法:它需要是#{loginBean.login},其中包含以下内容

  1. public String login() {
  2. //do any job with the associated values that you've got from the user,like persisting attempted login,etc.
  3. FacesContext facesContext = FacesContext.getCurrentInstance();
  4. ExternalContext extenalContext = facesContext.getExternalContext();
  5. RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check");
  6. dispatcher.forward((ServletRequest)extenalContext.getRequest(),(ServletResponse)extenalContext.getResponse());
  7. facesContext.responseComplete();
  8. return null;
  9. }

基本上,您需要做的就是调度到/ j_spring_security_check并将j_username和j_password作为请求参数.

使用纯HTML表单

基本上,在这个问题上没有特别需要混淆JSF表单,以防除了身份验证之外你不需要做一些额外的事情,而纯HTML表单足以让Spring Security完成它的工作.

  1. <form action="/j_spring_security_check" method="POST">
  2. <label for="j_username">User Id: </label>
  3. <input id="j_username" name="j_username" type="text" />
  4. <label for="j_password">Password: </label>
  5. <input id="j_password" name="j_password" type="password"/>
  6. <input type="submit" value="Submit"/>
  7. </form>

猜你在找的HTML相关文章