如何将Java变量传递到包含JavaScript的其他JSP页面?

时间:2018-12-10 20:12:25

标签: javascript java jquery ajax

我的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页面。对于这种情况的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

好,总结一下:

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

如果您还想发送“名称”参数,请在控制器方法中添加 @RequestParam字符串名称,然后调用ajax:

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