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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In this how can we pass objects, the problem is I am not able to type case when using request.getParameter
If data 1 and data 2 are objects then how can I type cast in my controller
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.
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
}

2 Comments

Could you please share the corresponding jsp as how to pass an object from there to here. Thank you.
Your JSP can just have a simple link like: <a href="/spring.html?data1=<%=data1 %>&data2=<%=data2 %>"> Hello </a> I suggest reading a little bit about Spring MVC tutorial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.