我想将参数从我的jsp页面传递给控制器。我找到了一种方法,因为 - 点击 -
<a href="ReqElement/reqTypeList.html?menuTab=CRM Setup">CRM Setup</a>
并在控制器类中 -
@RequestMapping("/reqTypeList")
public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Map<String, Object> map,HttpSession session,@RequestParam("id") String menu) {
但是如果我想传递多个参数,那么我必须添加更多@RequestParam作为 -
@RequestMapping("/reqTypeList")
public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Map<String, Object> map,HttpSession session,@RequestParam("id") String id,@RequestParam("roleId") String roleid,@RequestParam("funcId") String funcid) {
所以我的问题是 - 有没有其他方便的方法呢?因为在上述方式中,即在参数越来越多的情况下,方法参数的大小将增加。 我是Spring的新手。请帮忙。
答案 0 :(得分:14)
我不知道你对其他方便的方法的期望。这是最方便的方式。您可以准确指定所需的参数,这些是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
。
答案 1 :(得分:2)
正如Sotirios所说,@RequestParam
注释已经非常方便了。
如果您有很多请求参数,您可以始终指定Spring传递整个HttpServletRequest
,您可以从中访问所需的参数。
@RequestMapping("/reqTypeList")
public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Map<String, Object> map, HttpServletRequest request) {
String id = request.getParameter("id");
String roleid = request.getParameter("roleid");
String funcid = request.getParameter("funcid");
...
}
答案 2 :(得分:0)
使用request.getParameter
不是Spring方式。这是一个非常基本的问题,当Spring被制作时显然已经考虑过了,否则就会出现这样的框架。
如果您有许多参数使用所有这些参数创建一个DTO类,那么您可以编写控制器方法如下。
@RequestMapping("/test")
public String test(DTO dto)
{
// your DTO has all the fields of your request parameters given that the name of the
//request parameters and the variables of the dto have been kept same.
}