日期:2014-05-16 浏览次数:20538 次
/** * @author Bill * @version 2012-03-21 */ @SessionScoped @ManagedBean public class FormTokenBean { public static final String BEAN_NAME = "formTokenBean"; private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String resetToken() { return token = "T" + System.nanoTime(); } public boolean validateToken(String token) { return token != null && token.equals(this.token); } @PostConstruct public void init () { resetToken(); } }
/** * @author Bill * @version 2012-03-27 */ @FacesComponent("org.billxiong.faces.FormToken") public class FormTokenTag extends HtmlInputHidden{ public FormTokenTag() { setRendererType("javax.faces.Hidden"); // render as a standard InputHidden addValidator(new FormTokenValidator()); String token = FacesUtils.getObject("formTokenBean.token", String.class); setValue(token); } @Override public void decode(FacesContext context) { super.decode(context); String clientId = getClientId(context); String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId); if(submittedValue != null) { setSubmittedValue(submittedValue); } } }
<tag> <tag-name>formToken</tag-name> <component> <component-type>org.billxiong.faces.FormToken</component-type> </component> <attribute> <name>id</name> <required>false</required> <type>java.lang.String</type> </attribute> <attribute> <name>validatorMessage</name> <required>false</required> <type>java.lang.String</type> </attribute> </tag>
@FacesValidator("formTokenValidator") public class FormTokenValidator implements Validator{ @Override public void validate(FacesContext context, UIComponent uiComponent, Object o) throws ValidatorException { String token = o == null ? null : o.toString(); FormTokenBean tokenBean = FacesUtils.getObject(FormTokenBean.BEAN_NAME, FormTokenBean.class); if (null == token || null == tokenBean || !tokenBean.validateToken(token)) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, FacesUtils.getMessage("global.exception.tokenExpired"), "")); } } }
<h:form prependId="false"> <pgfn:formToken/> <h:messages errorClass="error-msgs" errorStyle="color: red;"/> <h:commandButton id="btnSubmit" action="#{xxxBean.xxxMethod}" value="Submit}" </h:form>