在spring mvc中将多个参数从视图传递到控制器

 阿门路亚_ 发布于 2023-02-06 12:10

我想将参数从我的jsp页面传递给控制器​​.我找到了一种方法,因为 - 点击 -

CRM Setup

在控制器类 -

@RequestMapping("/reqTypeList")
    public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Map map,HttpSession session,@RequestParam("id") String menu) {

但如果我想传递多个参数,那么我必须添加更多@RequestParam -

@RequestMapping("/reqTypeList")
public ModelAndView reqTypes(@ModelAttribute("reqElementSetup") ReqElementBean reqElBean, BindingResult result, Map map,HttpSession session,@RequestParam("id") String id,@RequestParam("roleId") String roleid,@RequestParam("funcId") String funcid) {

所以我的问题是 - 有没有其他方便的方法呢?因为在上述方式中,即在参数越来越多的情况下,方法参数的大小将增加.我是Spring的新手.请帮忙.

1 个回答
  • 我不知道你对其他方便方法的期望.这是最方便的方式.您可以准确指定所需的参数,这些是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在适当的时候使用.

    2023-02-06 12:11 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有