如何在spring-mvc中为同一个jsp页面在同一个Controller上创建两个动作

时间:2014-01-31 17:04:20

标签: java spring jsp spring-mvc

问题是我想在控制器中为同一个jsp页面创建两个动作(main.jsp)   第一个操作在重定向到main.jsp页面的时刻执行,以显示产品的详细信息,第二个操作与按钮相关联。 如何指示春天的愿望方法来调用?

控制器:

 @RequestMapping(value = "pages/main", method = RequestMethod.GET)
 public String detailProduct(final Model model, @RequestParam String id) {

    ProductDTO product = productService.getProduct(Long.parseLong(id));
    ProductModel productbean = mapperDozerBean.map(product, ProductModel.class);

    model.addAttribute("detailProduct", productbean);

    return detailView;
}

@RequestMapping(value = "pages/main", method = RequestMethod.GET)
public String addToCaddy(final Model model, @RequestParam String id,String action) {

    ProductDTO product = productService.getProduct(Long.parseLong(id));

    ...

    return caddyView;
}

jsp:main.jsp

...
    <div id="description">
            <h1>${detailProduct.name}</h1>
            <strong id="price">
                <span>previously &pound;299.00</span> ${detailProduct.price}dhs
            </strong>    
            <p>${detailProduct.description}</p> 
            <p>
                <button type="submit" name="addToCaddy" onclick="location.href='/main.do?id=${detailProduct.id}?'" class="continue" value="addToCaddy" >Ajouter au panier</button> ...

2 个答案:

答案 0 :(得分:1)

如评论中所述,将GET映射到一个方法,将POST映射到另一个方法。这是一个例子:

@RequestMapping(value = "pages/main", method = RequestMethod.GET)
public String doGet(
    final Model model, 
    @RequestParam final String id)
{
    ... setup for when the page displays
}

@RequestMapping(value = "pages/main", method = RequestMethod.POST)
public String doPost(
    final Model model, 
    @RequestParam String id,
    @RequestParam String action)
{
    ... Handle the request resulting from the button click (i.e. the post of a form).
}

答案 1 :(得分:1)

在发出给定页面的请求时,不必始终使用相同的URL。

例如,您可以像这样定义控制器:

@RequestMapping(value = "pages/main/detail", method = RequestMethod.GET)
public String detailProduct(final Model model, @RequestParam String id) {
    ...
}

@RequestMapping(value = "pages/main/addtocaddy", method = RequestMethod.GET)
public String addToCaddy(final Model model, @RequestParam String id,String action) {
   ...
}

然后在JSP上传入GET请求中的正确URL。