user10274438
user10274438

Reputation: 123

How to pass a java variable to a different jsp page containing javascript?

my java class:

@RequestMapping(value = "/front", method = RequestMethod.GET) public String onemethod(@RequestParam String name, Model model) { String str = "something"; model.addAttribute("str", str); return "jsppage"; }

jsp page:

        var arrayCollection = ${str}

With this code, I'm getting 404 exception on Tomcat. I'm unable to send java variable to a different jsp page. Any help would be appreciated for this case.

Upvotes: 0

Views: 58

Answers (1)

Konrad Malik
Konrad Malik

Reputation: 76

Ok to wrap this up:

2 choices:

  1. add variable to the model and access it directly in JSP
  2. make it a rest method and call from ajax

Examples:

Ad.1.:

Controller

import org.springframework.ui.Model;

@RequestMapping(value = "/front", method = RequestMethod.GET)
public String onemethod(Model model) throws IOException, ParseException {
    String str = "something";
    model.addAttribute("str", str);
    return "jsppage";
}

JSP ("jsppage")

var test = '${str}';

Ad.2.:

Controller

// just to show JSP
@RequestMapping(value = "/front", method = RequestMethod.GET)
public String onemethod() throws IOException, ParseException {
    return "jsppage";
}

// REST
@ResponseBody
@RequestMapping(value = "/rest", method = RequestMethod.GET)
public String secondmethod() {
    return "something";
}

JSP ("jsppage")

$.ajax({
    method : "get",
    url : "rest",
    dataType : 'text',
    success : function(data) {
        console.log(data);
    },
    error : function(e){
        console.log(e);
    }
});

If you want to also send "name" parameter, add @RequestParam String name to the controller method and call ajax like this:

$.ajax({
    method : "get",
    url : "rest",
    dataType : 'text',
    data : {"name" : "some name"},
    success : function(data) {
        console.log(data);
    },
    error : function(e){
        console.log(e);
    }
});

Upvotes: 1

Related Questions