0

It appears that a converter usually has two methods getAsObject() and getAsString(), which will convert Object into or from strings.

Why do we need to do this?

For example, in dataTable we can always bind an object with var. Why can't we do similar things here?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
ethanjyx
  • 1,970
  • 7
  • 28
  • 50

2 Answers2

4

In the end the client (usually a browser) will receive a rendered version of your JSF Component tree, which you usually built via .xhtml files.

The browser doesn't know about BigDecimals or Dates for example. If you write "1.003" in an input field of a form, how should the browser know whether it will be a String, or a float or a BigDecimal on server side? It cannot know that and also couldn't handle that. Thus the communication between server and browser is always via Strings. When the HTML gets rendered, the getAsString() method will be used. When processing the transmitted form inputs, JSF will use the getAsObject() to convert it back to the real type.

Why does var work in dataTables? Because here you will only go "one way". A dataTable will only display something and thus the generic toString() method can be used. A conversion to the Object isn't necessary in this case.

noone
  • 19,520
  • 5
  • 61
  • 76
0

I will copy and paste a great answer for balusc about why we should use a JSF converter(i do not remember the link of question itself)

JSF generates HTML. HTML is in Java terms basically one large String. To represent Java objects in HTML, they have to be converted to String. Also, when a HTML form is submitted, the submitted values are treated as String in the HTTP request parameters. Under the covers, JSF extracts them from the HttpServletRequest#getParameter() which returns String.To convert between a non-standard Java object (i.e. not a String, Number or Boolean for which EL has built-in conversions) you have to supply a custom Converter for your Entity class.This Converter implements two methods getAsString() method so that the desired Java Object is been represented in an unique string representation and getAsObject() method so that the HTTP request parameter can be converted back to the desired Java Object

Community
  • 1
  • 1
hanan Ahmed
  • 442
  • 3
  • 5