【问题标题】:how to create two actions on the same Controller for the same jsp page in spring-mvc如何在spring-mvc中为同一个jsp页面在同一个Controller上创建两个动作
【发布时间】:2014-01-31 17:04:20
【问题描述】:

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

控制器:

 @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> ...

【问题讨论】:

  • 控制器处理程序方法与 JSP 无关,它们处理对 URI 的请求。
  • 好吧,假设你是 Spring,你收到一个带有方法 GET 和 URL pages/main 的请求,你会选择调用哪个方法?如果你不给 Spring 一种选择一个而不是另一个的方法,它就无法做到。其中一个 URL 必须不同,或者必须在一种情况下传递参数,而不是另一种情况,或者标头,或者可以区分两个请求的东西。

标签: java spring jsp spring-mvc


【解决方案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。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多