springmvc:如何在没有控制器方法参数的情况下以mvc传递参数

spring-mvc : how to pass parameters in mvc without method arguments at the controller

本文关键字:参数 情况下 mvc 方法 控制器 springmvc      更新时间:2023-09-26

我的任务是创建我的控制器,而在方法签名处不传递任何参数。我很困惑,因为这是一个很大的挑战,我还没有在网上看到任何例子。例如:从我的jsp页面。

    <form:form method="POST" action="/project/searchResults" id="productSearchResultsForm">
        <input name="productRecord" id="productRecord" />
        <input name="resultEntity" id="resultEntity" type="hidden" />
        <input name="resultCode" id="resultCode" type="hidden" />
        <button type="submit" class="btn btn-primary btn-lg">Submit</button>
    </form:form>

我想将这三个输入传递给我的控制器,而不在方法签名处使用@RequestParameter和@ModelAttribute。到目前为止,这是我知道如何做到这一点的唯一方法。

@RequestMapping(value = "/productSearch", method = RequestMethod.GET)
public ModelAndView init(@ModelAttribute ("showroomCode") String showroomCode, HttpServletRequest request) {

    logger.info("<<<< initial page <<<<<<");
    logger.info("Showroom Code : " + showroomCode);
    HttpSession session = request.getSession();
    ModelAndView model = new ModelAndView("productSearch", "command",
            String.class);

     ShowroomUser user = new ShowroomUser();
     user.setUserId(1);
     session.setAttribute("usersession", user);
     session.setAttribute("showroomCode", showroomCode);
     logger.info(">>>>> initial page >>>>> ");
     return model;
}

我知道在Struts2中,您可以在Action类中声明全局变量,这样您就可以在方法中自动使用它们,而无需将它们放在方法签名中。有没有办法去除这个?

谢谢。

更新

我被要求在代码中的任何地方都不要使用HttpServlet请求和模型属性(请帮忙!

1)创建一个具有属性productRecord、resultEntity、resultCode的表单POJO。Ex MyForm.java

2) 在模型中设置此表单(在init方法中)例如:model.addAttribute("myForm", new MyForm())

3) 在您的jsp表单声明集中:<form:form commandName="myForm" >

4) 在控制器中(检索结果)@RequestMapping(value = "/productSearch", method = RequestMethod.POST) public ModelAndView postForm(MyForm myForm, HttpServletRequest request) {...}

然后可以使用myForm.getProductRecord()访问值。

我不知道你为什么要这么做。。但是,Spring将请求公开为ThreadLocal。你可以在当前线程上访问它,但在任何派生线程上都不能不传递它

以下是您的操作:

@RequestMapping("/whatever")
public ModelAndView controllerMethod() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
// Do as you want with the request without having to pass it in
}