Search code examples
javajavascriptspringspring-mvcmodelattribute

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


I was being tasked to create my controllers without passing any parameters at the method signature. I am quite baffled as this is quite challenge and I haven't really seen any examples at the net. For example: from my jsp page.

    <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>

I wanted to pass these three inputs to my controller without using @RequestParameter and @ModelAttribute at the method signature. As of now this is the only way I know how to do this.

@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;
}

I know that in Struts 2, you can just declare global variables in the Action class so you can automatically use them in the method without literally putting them in the method signature. Is there are way to remove this?

Thanks.

Update

I am asked not to use HttpServlet Request and Model Attributes at all anywhere in the code. :( Please help!


Solution

  • 1) Create a form POJO with your attribute productRecord, resultEntity, resultCode. Ex MyForm.java

    2) Set this form in the model (in your init method) Ex : model.addAttribute("myForm", new MyForm())

    3) In your jsp form declaration set : <form:form commandName="myForm" >

    4) In your controller (to retrieve result) @RequestMapping(value = "/productSearch", method = RequestMethod.POST) public ModelAndView postForm(MyForm myForm, HttpServletRequest request) {...}

    Then you can access values using myForm.getProductRecord() for example.