2

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.

user1562262
  • 95
  • 3
  • 7

2 Answers2

3

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • In this how can we pass objects, the problem is I am not able to type case when using request.getParameter – user1562262 Aug 03 '12 at 05:46
  • If data 1 and data 2 are objects then how can I type cast in my controller – user1562262 Aug 03 '12 at 05:52
  • You're making a conceptual mistake. HTML code cannot contain Java objects, but only a sequence of characters. A sequence of characters is in Java represented by a String. So you need to convert them to String and vice versa. Or you could just store them somewhere (database, session, etc) and pass some unique identifier. – BalusC Aug 03 '12 at 11:36
0

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
}
Jakub Kubrynski
  • 13,724
  • 6
  • 60
  • 85
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Could you please share the corresponding jsp as how to pass an object from there to here. Thank you. – user1562262 Aug 03 '12 at 05:58
  • Your JSP can just have a simple link like: ` Hello ` I suggest reading a little bit about [Spring MVC tutorial](http://static.springsource.org/docs/Spring-MVC-step-by-step/) – anubhava Aug 03 '12 at 08:55