开发者

what is the real use case scenario for spring conversion service

I was reading this questions

ConversionService in Spring

But i still dont get it under what scenarios we need to do conversion.

Can someone give me example of what can be rea开发者_JAVA技巧l life example of using conversion service in web apllicationj


Spring Webflow utilizes spring's conversion service. Webflow does not offer the availability of an InitBinder type method/annotation. So you tell Spring about all the conversions you want to be done for all flows. If the ConversionService was not available the binding support wouldn't be as available.


The Conversion Service can be used to directly convert between the UI and business objects.

Let's say that I have a webapp with a dropdown of Products. It's straightforward to define a ProductConversionService that converts from the value of the dropdown (say, id 4) to a Product. Now in my code (controller, API, etc) I just refer to a Product, and everything happens automatically.

In older UIs, I have seen lots of lots of code devoted to this conversion. I'll give a deliberately crude example:

String productIdParam = request.getParameter("productId");
// Validate that the param exists, is numeric, etc.....
Long productId        = Long.valueOf(productIdParam);
Product product       = productManager.findProduct(productId);

This code is also more difficult to test, since I have to create a mock request, give it a productIdParameter and so forth. Also I need to have the productManager available everywhere that this is needed.

With ConversionService, I can just put this in a JSP:

<form:select path="mystuff.product">
  <option value="1">Nook</option>
  <option value="2">Cranny</option>
</form:select>

When my Spring MVC controller gets the request, mystuff.getProduct() has the selected product. Clean and simple. And I can use this outside the web tier as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜