如何将java变量传递到另一个包含javascript的jsp页面



我的java类:

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

jsp页面:

var arrayCollection = ${str}

有了这段代码,我在Tomcat上得到了404异常。我无法将java变量发送到另一个jsp页面。如有任何帮助,我们将不胜感激。

可以结束:

2种选择:

  1. 将变量添加到模型中,并在JSP中直接访问它
  2. 将其作为rest方法并从ajax调用

示例:

Ad.1.:

控制器

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:

控制器

// 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);
}
});

如果您还想发送"name"参数,请将@RequestParam String name添加到控制器方法中,并像这样调用ajax:

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

相关内容

最新更新