我有一个在我的JSF应用程序中使用BigDecimal类型的要求。
所以我使用BigDecimal Converter进行如下转换:
<h:inputText value="#{priceManager.price}">
<f:converter converterId="javax.faces.BigDecimal"/>
</h:inputText>
这很好。
除了这种转换,我还想限制
显然f:converter
没有灵活f:convertNumber
。
那么如何实现以上目标呢?
如果需要覆盖默认的Converter,我会做的,但是我从来没有做过。
请给我一些建议。
Mojarra版本-2.1
我不知道让转换器进行验证是否是一种好习惯,但这是我所看到的最干净的方法。这个转换器对我来说很好用:
package teststuff;
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import org.apache.commons.lang3.math.NumberUtils;
@FacesConverter("bigDecimalConverter")
public class BigDecimalConverter implements Converter {
private static final BigDecimal UPPER_LIMIT = new BigDecimal(9999);
private static final BigDecimal LOWER_LIMIT = new BigDecimal(-9999);
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
if (!NumberUtils.isNumber(value)) {
throw new ConverterException(new FacesMessage("not a number"));
}
if (value.contains(".")) {
String decimalPlace = value.substring(value.indexOf("."));
if (decimalPlace.length() > 3) { // 3 as decimal point is included in the String
throw new ConverterException(new FacesMessage(
"too many numbers after decimal point"));
}
}
BigDecimal convertedValue = new BigDecimal(value).setScale(2,
RoundingMode.HALF_UP);
if (convertedValue.compareTo(UPPER_LIMIT) > 0) {
throw new ConverterException(new FacesMessage(
"value may not be greater than " + UPPER_LIMIT));
}
if (convertedValue.compareTo(LOWER_LIMIT) < 0) {
throw new ConverterException(new FacesMessage(
"value may not be less than " + LOWER_LIMIT));
}
return convertedValue;
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return ((BigDecimal) value).toString();
}
}
我只是这样使用它:
<h:form>
<h:inputText value="#{priceManager.price}" converter="bigDecimalConverter"/>
<h:messages/>
<h:commandButton value="submit"/>
</h:form>
感谢您对此的任何反馈。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句