Implementando conversor de moeda com JSF
06/04/2009 | Por Samuel Delfim | Categoria: DESENVOLVIMENTO WEBAlgumas pessoas já devem ter passado pelo problema de criar um conversor de moedas em JSF que funcione bem para diferentes países. Segue abaixo uma sugestão de como implementar um conversor legal.
O primeiro passo é implementar a classe de conversor. Segue abaixo a classe:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class MoedaConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) { FacesContext fc = FacesContext.getCurrentInstance(); Locale l = fc.getViewRoot().getLocale(); if (value != null) { value = value.trim(); if (value.length() > 0) { try { return new BigDecimal(NumberFormat. getNumberInstance(l).parse( value).doubleValue()); } catch (ParseException e) { e.printStackTrace(); } } } return null; } @Override public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) { if (value == null) { return ""; } if (value instanceof String) { return (String) value; } try { FacesContext fc = FacesContext.getCurrentInstance(); Locale l = fc.getViewRoot().getLocale(); NumberFormat formatador = NumberFormat.getNumberInstance(l); formatador.setGroupingUsed(true); return formatador.format(value); } catch (Exception e) { throw new ConverterException("Formato não é número."); } } } |
Depois deve-se adicionar o seguinte trecho no arquivo faces-config.xml:
1 2 3 4 | <converter> <converter-id>MoedaConverter</converter-id> <converter-class>com.thinkworks.converter.DoubleConverter</converter-class> </converter> |
Para utilizá-lo agora basta utilizar da seguinte maneira:
Não se esqueça que este conversor não é também máscara de javascript. Então é importante criar a máscara e adicionar no componente para facilitar a vida do usuário.
É isto aí pessoal. Qualquer problema avisem.
[]s,


