spring - 在spring mvc中将多个参数从 View 传递给 Controller

标签 spring spring-mvc jstl

我想将参数从我的 jsp 页面传递到 Controller 。我找到了一种方法来这样做 -
点击-

<a href="ReqElement/reqTypeList.html?menuTab=CRM Setup">CRM Setup</a>

并在 Controller 类中-
@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 的新人。请帮忙。

最佳答案

我不知道您对其他方便的方法有何期望。这是最方便的方式。您可以准确指定所需的参数,而这些参数正是 Spring 给您的。

这是正确的方法。

这是你的问题陈述

Because in such above way i.e. in case of more and more parameters the size of method parameter will get increased.



首先,编写 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在适当情况下。

关于spring - 在spring mvc中将多个参数从 View 传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20949777/

相关文章:

java - 如何给com.myproject.api下的所有 Controller 添加 "api"前缀?

spring - 在 Spring 上模拟 @Validated 带注释的 Controller 方法的 ConstraintValidator

spring - 如何正确设置速度的加载器路径

java - 如何在XML bean配置中继承代理对象

java - Spring 同步 Hibernate 和 JMS 事务

spring - 配置类中@EnableWebSecurity 的原因

java - 为 spring ConfigurationProperties 子类使用构造函数注入(inject)

java - 在 JSP 中打印 HashMap

java - org.apache.jasper.JasperException : The absolute uri: http://java. sun.com/jsp/jSTL/core 无法解析

database - 从数据库中检索图像并使用 JSTL 在 JSP 中显示它