user1562262
user1562262

Reputation: 95

Sending parameters from JSP to spring controller

I am developing a web app using spring MVC. I am passing the parameters from JSP to spring controller in the below format. Like I have to pass two parameters so I am doing

<a href="/spring.html?data1=<%=data1 %>?data2=<%=data2 %>"> Hello </a>

My assumption is that in the spring controller, I can receive the output as the following

data1= request.getAttribute("data1");
data2= request.getAttribute("data2");

Is this the correct way to pass the parameters . I have dry run my code many times still my pages gives null pointer so I doubt whether it is because of this . Could you ppl please let me know about this. Thank you.

Upvotes: 2

Views: 9899

Answers (2)

anubhava
anubhava

Reputation: 786091

If it is Spring MVC controller then your don't need to do call request.getParameter. You can just define your method like this and arguments will be auto-populated by MVC framework:

@RequestMapping(value="/myRequest", method=RequestMethod.GET)
@ResponseBody
public String handleMyRequest(
        @RequestParam String data1,
        @RequestParam String data2
        ) {
   // your handler code here
   // you will have data1 and data2 automatically populated by Spring MVC
}

Upvotes: 0

BalusC
BalusC

Reputation: 1109635

There are at least 2 technical mistakes:

  1. You should get request parameters as request parameters, not as request attributes.

    data1 = request.getParameter("data1");
    data2 = request.getParameter("data2");
    
  2. The request parameter separator is &, not ?. The ? is the request query string separator.

    <a href="/spring.html?data1=<%=data1 %>&data2=<%=data2 %>"> Hello </a>
    

There's by the way a third mistake, but that's more a design matter. Scriptlets are discouraged since a decade.

Upvotes: 3

Related Questions