我创建了一个简单的JSF登录页面,我正在尝试将其与
spring安全性集成.
这是login.xhtml中的表单元素
- <h:form>
- <h:outputLabel value="User Id:" for="userId"/>
- <h:inputText id="j_username" label="User Id"
- required="true" value="#{loginBean.name}" >
- </h:inputText>
- <h:outputLabel value="Password: " for ="password"/>
- <h:inputSecret id="j_password" value="#{loginBean.password}" />
- <h:commandButton value="Submit" action="#{j_spring_security_check}" />
- </h:form>
但渲染的html页面有类似下面的内容.看一下表单操作和输入标签的名称
表单元素
- <form id="j_idt6" name="j_idt6" method="post"
- action="/jsfproject2/faces/login.xhtml"
- enctype="application/x-www-form-urlencoded">
和输入标签
- User Id:</label><input id="j_idt6:j_username" type="text"
- 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:
- <h:form prependId="false">
- <h:outputLabel value="User Id: " for="userId" />
- <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" />
- <h:outputLabel value="Password: " for ="password" />
- <h:inputSecret id="j_password" value="#{loginBean.password}" />
- <h:commandButton value="Submit" action="#{loginBean.login}" />
- </h:form>
请注意,#{j_spring_security_check}是一个错误的操作方法:它需要是#{loginBean.login},其中包含以下内容:
- public String login() {
- //do any job with the associated values that you've got from the user,like persisting attempted login,etc.
- FacesContext facesContext = FacesContext.getCurrentInstance();
- ExternalContext extenalContext = facesContext.getExternalContext();
- RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check");
- dispatcher.forward((ServletRequest)extenalContext.getRequest(),(ServletResponse)extenalContext.getResponse());
- facesContext.responseComplete();
- return null;
- }
基本上,您需要做的就是调度到/ j_spring_security_check并将j_username和j_password作为请求参数.
使用纯HTML表单
基本上,在这个问题上没有特别需要混淆JSF表单,以防除了身份验证之外你不需要做一些额外的事情,而纯HTML表单足以让Spring Security完成它的工作.
- <form action="/j_spring_security_check" method="POST">
- <label for="j_username">User Id: </label>
- <input id="j_username" name="j_username" type="text" />
- <label for="j_password">Password: </label>
- <input id="j_password" name="j_password" type="password"/>
- <input type="submit" value="Submit"/>
- </form>