gpt4 book ai didi

spring - Spring中结合GET和POST请求方法

转载 作者:行者123 更新时间:2023-12-02 03:40:52 24 4
gpt4 key购买 nike

我有一个支持 GETPOST 请求的资源。这里是示例资源的示例代码:

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter, two @RequestParam parameters, HttpServletRequest request)
throws ParseException {
LONG CODE
}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, BindingResult result)
throws ParseException {
SAME LONG CODE with a minor difference
}

这两个方法中的代码实际上是相同的,除了变量定义之外。使用 method = {RequestMethod.POST, RequestMethod.GET} 和内部一个简单的 if 可以轻松组合这两种方法。我尝试过,但它不起作用,因为这两种方法最后有一个不同的参数,即 HttpServletRequestBindingResult (@RequestParam 不是必需的,因此在 POST 请求中也不需要)。有什么想法如何结合这两种方法吗?

最佳答案

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
@RequestParam(required = false) String parameter1,
@RequestParam(required = false) String parameter2,
BindingResult result, HttpServletRequest request)
throws ParseException {

LONG CODE and SAME LONG CODE with a minor difference
}

如果@RequestParam(required = true)那么你必须传递parameter1,parameter2

使用 BindingResult 并根据您的条件请求它们。

另一种方式

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
two @RequestParam parameters, HttpServletRequest request) throws ParseException {

myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
BindingResult result) throws ParseException {

myMethod();

do here your minor difference
}

private returntype myMethod(){
LONG CODE
}

关于spring - Spring中结合GET和POST请求方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com