我有一個jsp頁面,其中包含用於將ne項添加到系統的表單。在那裏,我需要選擇新項目所屬的類別。我需要使用spring從數據庫填充這個下拉列表。對於表單提交,我寫了一個名爲ItemController.java的控制器類,其中下拉元素是我需要填充的。但是,該填充列表項需要從另一個名爲CategoryController.java的控制器類中調用。我嘗試了很多方法,但仍然無法做到這一點,因爲仍然犯了錯誤。有人可以看看這個請嗎?在彈簧中從數據庫填充下拉列表
這是我的代碼。
addItem.jsp
<form:form class="form-horizontal" role="form" id="frmAddItem" action="/admin/items/add_item" method="post" commandName="command">
<fieldset class="scheduler-border">
<div class="form-group">
<div class="row">
<label for="selectCat" class="col-xs-3 control-label">
Category
</label>
<div class="col-xs-5">
<form:select class="form-control" id="selectCat" path="categoryName">
<form:option value="-" label="--Select Category--"/>
<form:options items="${listCat}" />
</form:select>
<span id="catErr" class="input-group-error"></span>
</div>........
ItemController.java
@Controller
@RequestMapping(value = "/items")
public class ItemController {
private static final Logger LOG = LogManager.getLogger(ItemController.class);
@Autowired
private ItemRepository item;
@Qualifier("categoryRepository")
@Autowired
private CategoryRepository category;
/**
* Add new item view
*/
//For viewing the add item form
@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView showAddItem() {
return new ModelAndView("addItem", "command", new Item());
}
//For submitting the add new item
@RequestMapping(value = "/add_item")
public String addItem(@ModelAttribute("newItem") Item newItem) throws SQLIntegrityConstraintViolationException {
System.out.println("First Name:" + newItem.getItemName());
int a = item.add(newItem);
if (a == 1)
return "redirect:add";
// model.setViewName("addItem");
else
// System.out.println("Error in item add");
return "redirect:add";
// return model;
}
CategoryController.java
@Controller
@RequestMapping("/items")
public class CategoryController {
private static final Logger LOG = LogManager.getLogger(CategoryController.class);
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ItemRepository item;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView showAddItem() {
ModelAndView model = new ModelAndView();
List<Map<String, Object>> listCat = categoryRepository.viewCategoryList();
model.addObject("listCat", listCat);
return new ModelAndView("addItem", "command", new Item());
}
它看起來你有映射/項目/添加映射到兩個不同的控制器 – jmw5598
https://www.mkyong.com/spring-mvc/spring-mvc-dropdown-box-example /你的問題是你有地圖列表。在這個例子中只有鍵值對的映射。我認爲你必須循環list.Within循環,你可以嘗試
類型的代碼或帶鍵和值的選項標籤 – Sanka