繁体   English   中英

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

[英]how to create two actions on the same Controller for the same jsp page in 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> ...

如评论中所述,将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).
}

在从给定页面发出请求时,不必始终使用相同的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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM