我想将参数从我的jsp页面传递给控制器.我找到了一种方法,因为 - 点击 -
CRM Setup
在控制器类 -
@RequestMapping("/reqTypeList") public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Mapmap,HttpSession session,@RequestParam("id") String menu) {
但如果我想传递多个参数,那么我必须添加更多@RequestParam -
@RequestMapping("/reqTypeList") public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Mapmap,HttpSession session,@RequestParam("id") String id,@RequestParam("roleId") String roleid,@RequestParam("funcId") String funcid) {
所以我的问题是 - 有没有其他方便的方法呢?因为在上述方式中,即在参数越来越多的情况下,方法参数的大小将增加.我是Spring的新手.请帮忙.
我不知道你对其他方便方法的期望.这是最方便的方式.您可以准确指定所需的参数,这些是Spring为您提供的参数.
这是正确的方法.
这是你的问题陈述
因为在上述方式中,即在参数越来越多的情况下,方法参数的大小将增加.
首先,编写Spring MVC是为了让您的生活更轻松,除其他原因外,还要尽可能多地删除Servlet API的依赖项.
其次,拥有大量方法参数绝对没有错.你甚至不是自己调用这个方法,Spring就是它拥有使用正确参数调用它所需的所有工具.
最后,整个观点@RequestParam
是你不使用HttpServletRequest#getParameter(String)
.像这样的方法
@RequestMapping public String someMethod(@RequestParam String param1, @RequestParam String param2) { // use the request parameters }
相当于
@RequestMapping public String someMethod(HttpServletRequest request) { String param1 = request.getParameter("param1"); String param2 = request.getParameter("param2"); if (param1 == null) { throw new // some bad request exception } if (param2 == null) { throw new // some bad request exception } // use the request parameters }
我希望你看到你如何编写更多样板,复杂的代码.如果您需要为缺少的请求参数添加默认值,这会变得更糟.使用Spring MVC
@RequestMapping public String someMethod(@RequestParam(defaultValue = "some value") String param1) // use the request parameters }
没有它
@RequestMapping public String someMethod(HttpServletRequest request) String param1 = request.getParameter("param1"); if (param1 == null) { param1 = "someValue"; } // use the request parameters }
如果您的API需要更多请求参数,请继续添加它们,但要让您的生活变得简单并@RequestParam
在适当的时候使用.