What is the purpose of converters in jsf? [duplicate]

心已入冬 提交于 2019-12-12 03:29:13

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19763346/what-is-the-purpose-of-converters-in-jsf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!