我有一个jsp页面,其中包含一个用于向系统添加项目的表单。在那里,我需要选择新项目所属的类别。我需要使用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());
}
答案 0 :(得分:1)
您正尝试将{2}模型添加到ModelAndView
类中showAddItem
方法内的CategoryController
对象中,如果您要将多个对象添加到ModelAndView
,这将无效您可以使用Map
或仅使用Model
类。
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String showAddItem(Model model) {
List<Map<String, Object>> listCat = categoryRepository.viewCategoryList();
model.addAttribute("listCat",listCat);
model.addAttribute("command",new Item());
return "addItem";
}
因为您尝试填充List of Maps
的下拉列表,您可能想要更改jsp中的当前代码。
<select name='lists'>
<c:forEach var="list" items="${listCat}">
<option id="${list.key}" value="${list.value.getName()}">${list.value.getName()}</option>
</c:forEach>
</select>
更改表单中的commandname属性
commandName="command"