目前代碼
我只是假設你使用的是基於您的HTML以下類,所以讓我們把它們作爲一個起點。
/* This may be called City in your code */
public class Item {
private Long id;
private String description;
// getter/setter/constructor here...
}
public class ContactForm {
private Long cityId;
// getter/setter/constructor here...
}
現在我們能做些什麼來解決您的問題?
Spring爲特定類添加轉換器提供了一種簡單的方法,例如,您不必擔心將字符串轉換爲Year對象。同樣的技術也可以用於其他類,比如你的Item類!讓我們來看看它:
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class StringToItemConverter implements Converter<String, Item> {
@Override
public Item convert(String source) {
if(source != null) {
try {
Long id = Long.parseLong(source);
return /* insert your logic for getting an item by it's id here */;
} catch(Exception e) {
return null;
}
}
return null;
}
}
上面的代碼是由春天時,它會嘗試把一個字符串(從你的表單輸入)和實際的Java字段類型Item
自動執行。所以如果我們稍微改變一下你的ContactForm類,spring會自動爲給定的id賦值Item對象。
public class ContactForm {
/* Note that cityId now has all the information you need (id and description) You should however consider renaming it to city. Don't forget to change the th:field name too! ;) */
private Item cityId;
// getter/setter/constructor here...
}
你使用Spring庫的工作?
如果你將你的物品存儲在數據庫中,你很可能會使用CrudRepository。在這種情況下,代碼可能看起來像這樣。假設您的Repository類被命名爲ItemRepository。
@Component
public class StringToItemConverter implements Converter<String, Item> {
private ItemRepository itemRepository;
@Autowired
public void setItemRepository (ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@Override
public Item convert(String source) {
if(source != null) {
try {
Long id = Long.parseLong(source);
return itemRepository.findOne(id);
} catch(Exception e) {
return null;
}
}
return null;
}
}
上面的代碼會嘗試通過在數據庫中查找的ID了繩子從形式上轉化爲實際Item
-object。所以我們要麼得到Item
,要麼是null,如果出現任何問題(例如,如果沒有該id的項目或String不能被解析爲很長時間)。
感謝您的詳細解答。所以爲了獲得項目對象,我必須擊中數據庫?我希望像th:value =「$ {item}」這樣的東西,並且發佈了Item對象來構建它,而不需要打DB。我想在angular JS ng-model =「item」中做一些事情,當我發佈ContactForm時,spring會自動從@RequestBody中構造ConcatForm和Item對象。但我知道這是一個限制,當我們使用服務器端模板 – Mukun
你不必從數據庫中查找它。你會如何正常地在你的代碼中查找它的id? –
我會使用itemRepository.findOne(id);如果對象不在高速緩存中,那麼它會擊中數據庫的權利? – Mukun