简体   繁体   English

如何使用request.getparameter在Java控制器中获取JavaScript变量?

[英]How can I get a JavaScript variable within my java controller using request.getparameter?

I have a javascript variable within my JSP, I was wondering if there was a way I could pick this up in my java controller using the HTTP request.getparameter? 我的JSP中有一个javascript变量,我想知道是否有一种方法可以使用HTTP request.getparameter在Java控制器中进行处理? This is so I can pass the string value I need into my hibernate method. 这样一来,我便可以将所需的字符串值传递给休眠方法。

Java script is on browser side where java code is server side. Java脚本位于浏览器端,而Java代码位于服务器端。 You can not pass like this but you can do form-submission, or using URL parameter or using AJAX calls. 您不能像这样通过,但是可以提交表单,或者使用URL参数或使用AJAX调用。 Below is form-submission example: 以下是表单提交示例:

HTML: you should wrap the hidden field insdie <form> tag HTML:您应该将隐藏字段insdie <form>标记包装起来

<form>
<input type="hidden" id="hiddenId" name="hiddenId"/>
</form

JavaScript: JavaScript的:

document.getElementById("hiddenId").value=yourValue;

Then do a form submission, you will be able to get at server side using 然后进行表单提交,您将可以使用

request.getParameter("hiddenId")

You can send your javascript variable value with your URI like:- 您可以使用URI发送javascript变量值,例如:

http://localhost:8080/myApp?myVariable="value"

And at server side you can simply use request.getParameter("myVariable") to retrieve the value of your variable. 在服务器端,您只需使用request.getParameter("myVariable")即可检索变量的值。

I have two approaches - 我有两种方法-
1.Using Form Submit 1.使用表格提交
a)Define Form in JSP a)在JSP中定义表单
b)Define Hidden field with name inside form b)在表单中定义名称的隐藏字段
c)Set javascript variable value in html hidden fields (can be achieved using jquery on some event) c)在html隐藏字段中设置javascript变量值(可以在某些事件上使用jquery实现)
d)Submit form d)提交表格

2.Using Ajax call 2.使用Ajax通话
a)create ajax request in jquery a)在jquery中创建ajax请求
b)set javascript variable value as params of ajax. b)将javascript变量值设置为ajax的参数。

With both approach you can access variable using request.getParameter() at server side where controller resides. 通过这两种方法,您都可以在控制器所在的服务器端使用request.getParameter()访问变量。

 var value = gnval;
 $.ajax({
   method: "POST",
   url: "yoururl",
   data: {gnval: value}
 });

For all those curious this is how I used AJAX to do this. 对于所有好奇的人,这就是我使用AJAX做到这一点的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM