【问题标题】:How to pass a java variable to a different jsp page containing javascript?如何将java变量传递给包含javascript的不同jsp页面?
【发布时间】:2018-12-10 20:12:25
【问题描述】:

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

【问题讨论】:

标签: javascript java jquery ajax


【解决方案1】:

好的,总结一下:

2 个选择:

  1. 在模型中添加变量,直接在JSP中访问
  2. 将其设为休息方法并从 ajax 调用

例子:

广告 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}';

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

【讨论】:

  • 谢谢。我做到了。我将如何在 javascript 中检索它?
  • 好的,现在你的问题看起来不一样了,你有两个选择:回到前面的例子,用 "var something = '${str}' 你应该在 JSP 中有你的字符串 "str",或者做你现在做的事情,但是将@ResponseBody添加到控制器方法中,并在ajax的“data”属性中发送你的“name”参数(或将其设置为@RequestParam(required = false)字符串名称)。然后你会有javascript中“jsppage”下的任何内容。您也可以尝试将“dataType”更改为文本,因为您返回一个字符串。
  • 我按照你说的做了,使用@responsebody 我在本地主机上获取数据。但它不会用到javascript。我的ajax似乎有问题。你能看看吗?
  • 请查看我的编辑并检查两个示例中的任何一个
  • 我想我会选择第一个。删除请求参数后它可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 2012-03-18
  • 2011-07-19
相关资源
最近更新 更多