JSP表单标记操作属性URI Spring MVC

时间:2015-10-03 12:43:51

标签: java jsp spring-mvc uri

我有这样的控制器

   @Controller
    @RequestMapping("/pizza")
    public class PizzaController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String viewPizzas(Model model) {
        model.addAttribute("pizzas",
                pizzaService.getAllPizzas());
        return "pizzas";
    }
     @RequestMapping(value = "/create", method = RequestMethod.GET)
        public String create() {
            return "newpizza";
        }

        @RequestMapping(value = "/addnew", method = RequestMethod.POST)
        public String addNewPizza(@ModelAttribute Pizza newPizza) {
            pizzaService.addPizza(newPizza);
            return "redirect:";
        }

        }

        @RequestMapping(value = "/edit", method = RequestMethod.GET)
        public String edit(@RequestParam("pizzaid") Long id, 
                Model model) {
            if (id<=0) throw new IllegalArgumentException("ID<0");
            Pizza pizza = pizzaService.getPizzaById(id);
            if (pizza == null) 
                throw new NotFoundPizzaException("Pizza id" + id + " not found" );
            model.addAttribute("pizza", pizza);
            return "newpizza";
        }
    }

和JSP的:pizzas.jsp

    <body>
        <table border="1">
           ......................
                        <form method="get" action="edit" >
                            <input type="hidden" name="pizzaid" value="${pizza.id}" />
                            <input type="submit" value="Edit" />
                        </form>        

        </table>
        <a href="create"> Create new pizza </a> <br/>
    </body>

和newpizza.jsp

<body>
        <form action="addnew" method="post">
                   <input type="hidden" name="id" value="${pizza.id}"/>
            Name : <input type="text" name="name" value="${pizza.name}"/></br>
            Type : <input type="text" name="type" value="${pizza.type}"/></br>
            Price : <input type="text" name="price" value="${pizza.price}"/></br>
            <input type="submit" value="Create"/></br>
        </form>
    </body>

这很好用,直到我尝试在我的控制器中更改URI,例如:

@RequestMapping(value = "/addnew/add", method = RequestMethod.POST)
@RequestMapping(value = "/edit/add", method = RequestMethod.GET)

和表格标签:

<form action="addnew/add" method="post">
<form action="edit/add" method="get">

我得到HTTP Status 404。我有一个问题:我应该如何使用action属性,以便有机会请求这样的地图@RequestMapping(value = "/edit/add" ......

1 个答案:

答案 0 :(得分:2)

您最可能的问题是,您当前使用action属性的方式将其视为相对路径,并将其添加到当前网址。根据浏览器中的当前URL,它们可能会或可能不起作用。

要避免这种情况,请使用action属性中的绝对路径,例如

<form action="${pageContext.request.contextPath}/pizza/addnew/add" method="post">
<form action="${pageContext.request.contextPath}/pizza/edit/add" method="get">