spring mvc requestmapping问题

时间:2013-12-04 16:27:00

标签: spring spring-mvc data-binding

我正在使用spring mvc app(我在spring mvc中的新功能)。

这是我的控制者:

@Controller
@RequestMapping("/prueba2")
public class controller2 {

Stock stock=new Stock();
List stockList=new ArrayList<Stock>();
ApplicationContext appContext = new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
StockBo stockBo = (StockBo)appContext.getBean("stockBo");


@RequestMapping(method = RequestMethod.GET)
public Stock returnCustomer(ModelMap model) {
    stock=stockBo.findByStockCode("7668");
    model.addAttribute("miStock", stock);
    return stock;


}

@RequestMapping(method = RequestMethod.GET)
public @ResponseBody
List<Stock>returnAll(ModelMap model) {

    stockList=stockBo.findAll();
    System.out.println("lista objetos--->"+stockList.toString());
    model.addAttribute("listaStock", stockList);
    return stockList;


}

public StockBo getStockBo() {
    return stockBo;
}

public void setStockBo(StockBo stockBo) {
    this.stockBo = stockBo;
}
}

这是我的观点:

<%@ taglib prefix="c"
       uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>

<h1>Message : "Por fin funciona!!!"</h1>

<table border="1">
<tr>
<th>Codigo Stock</th>
<th>Nombre Stock</th>
</tr>
<tr>
<td>${miStock.stockCode}</td>
<td>${miStock.stockName}</td>
</tr>

</table>




<h1>Tabla con lista de stock</h1>

    <table>

        <tr>
            <th>Codigo Stock</th>
            <th>Nombre Stock</th>

        </tr>

            <c:forEach items="${listaStock}" var="stock">
        <tr>
            <td>
                ${stock.stockCode}
            </td>
            <td>
                ${stock.stockName}
            </td>

         </tr>

        </c:forEach>

    </table>

  <ul>codigo stock
   <c:forEach items="${listaStock}" var="stock">
  <li> <c:out value="${stock.stockCode}"></c:out>  </li>
    </c:forEach>
  </ul>
</body>
</html>

我想要做的是在同一个JSP中显示2个表,我不想去另一个页面显示每个表,但我不太清楚如何使用“requestmapping”使其工作。现在只是向我展示第一张桌子。

1 个答案:

答案 0 :(得分:0)

如果您需要访问库存清单以及同一JSP中的单个库存项目,则只需将库存清单添加到模型中。

@RequestMapping(method = RequestMethod.GET)
public Stock returnCustomer(ModelMap model) {
    stock = stockBo.findByStockCode("7668");
    model.addAttribute("miStock", stock);
    model.addAttribute("listaStock", stockBo.findAll()); // Add the list to model
    return stock;
}

或者,您可以将其设置为单独的方法,如果它在同一控制器中的许多方法中使用,将节省重复。

@RequestMapping(method = RequestMethod.GET)
public Stock returnCustomer(ModelMap model) {
    stock = stockBo.findByStockCode("7668");
    model.addAttribute("miStock", stock);
    return stock;
}

@ModelAttribute("listaStock") 
public List<Stock> getAllStock() { // Called and set by Spring automatically
    return stockBo.findAll();
}