如何将参数从 servlet 传递给 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25983786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass parameters from servlet to JavaScript
提问by E235
I am working on a board game with dynamic board size of 5x5,...,8x8
This should be a game that runs on a web.
我正在开发一个动态棋盘大小为 5x5,...,8x8 的棋盘游戏。
这应该是一个在网络上运行的游戏。
I am working with NetBeans and tomcat as the server for testing.
我正在使用 NetBeans 和 tomcat 作为测试服务器。
I have the GameSettings.html which the user choose the board size and press submit.
我有 GameSettings.html,用户可以在其中选择棋盘大小并按提交。
The data is being sent to servlet named: GameSettingsServlet.java
数据被发送到名为:GameSettingsServlet.java 的 servlet
There I pull out the boardSize and parse it to an integer:
在那里我拉出 boardSize 并将其解析为一个整数:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
createEngine(request);
processRequest(request, response);
}
private void createEngine(HttpServletRequest request)
{
int boardSize = Integer.parseInt(request.getParameter("boardSize"));
int numberOfPlayers = Integer.parseInt(request.getParameter("numberOfPlayers"));
m_Engine = new Engine(boardSize, numberOfPlayers );
}
I want to create the board with javaScript so I need to send the boardSize parameter to the javaScript (which should run on BoardGame.html) in order to know how much rows and columns to create.
我想用 javaScript 创建板,所以我需要将 boardSize 参数发送到 javaScript(它应该在 BoardGame.html 上运行),以便知道要创建多少行和列。
How can I pass the boardSize to the javaScript or HTML ?
如何将 boardSize 传递给 javaScript 或 HTML ?
I searched on the web but I found only about JSP and I need it on HTML.
我在网上搜索,但我只找到了 JSP 并且我需要它在 HTML 上。
回答by andrex
In your servlet you go like this
在您的 servlet 中,您像这样
request.setAttribute("boardsize" boardSize);
Thats the name of the atrribute and the variable.
这就是属性和变量的名称。
The in the jsp page you go
你去的jsp页面
<% int boardSize = (Integer) request.getAttribute("boardsize"); %>
Then when you are going to use it in javasceipt you do it like this
然后当你打算在 javasceipt 中使用它时,你可以这样做
<script>var boardsize =<%= boardSize%>;
Also when you are using java you need to use jsp instead of html if you want to access classes and variable set by servlet on the front end.
此外,当您使用 java 时,如果要访问前端 servlet 设置的类和变量,则需要使用 jsp 而不是 html。
You can start from here http://docs.oracle.com/cd/E21764_01/web.1111/e13712/basics.htm
你可以从这里开始http://docs.oracle.com/cd/E21764_01/web.1111/e13712/basics.htm
Once you already understands the whole servlet to jsp logic it should be be a piece of cake passing variable proccessed by servlets.
一旦您已经了解了整个 servlet 到 jsp 的逻辑,那么传递由 servlet 处理的变量应该是小菜一碟。
As per the comments pointed out there is also a way of doing ajax and servlet can return values if you use ajax request. You do need a response to do this.
根据评论指出,如果您使用 ajax 请求,还有一种方法可以执行 ajax 和 servlet 可以返回值。你确实需要一个回应来做到这一点。
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response){
int boardSize = Integer.parseInt(request.getParameter("boardSize"));
int numberOfPlayers = Integer.parseInt(request.getParameter("numberOfPlayers"));
m_Engine = new Engine(boardSize, numberOfPlayers );
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.write("<board>" + boardSize + "</board>");
out.flush();
}
I bet when you read more about java, servlets, jsp you will learn more. Just put more effort in reading so you can learn it's not really that hard to understand but just be patient if you are finding difficulty in doing so.
我敢打赌,当您阅读更多有关 java、servlets、jsp 的内容时,您会学到更多。只需在阅读上付出更多努力,这样您就可以了解它并不难理解,但如果您发现这样做有困难,请耐心等待。
回答by Bhushan Mahajan
The below given code can serve the response from JSP to Servlet . //setParameter -- getparameter
下面给出的代码可以提供从 JSP 到 Servlet 的响应。//setParameter -- 获取参数
// jsp --
<form id="form1" name="form1" runat="server"
action="/YFCustomize/hello" method ="Post" >
<input id="MBA_DB" name="MBA_DB" type="text" value="11111" />
<input id="Button2" type="submit" value="Validate" />
</form>
// to Servlet -
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String txtMBA_DB=request.getParameter("MBA_DB");
String txtMBA_ip=request.getParameter("MBA_ip");
}
The below given code can serve the response from Servlet to JSP . //setAttribute -- getAttribute
下面给出的代码可以提供从 Servlet 到 JSP 的响应。//setAttribute -- 获取属性
// Servlet -
request.setAttribute("MBA_DB_VALIDATE",MBA_DB_VALIDATE);
request.setAttribute("YF_DB_VALIDATE",YF_DB_VALIDATE);
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/YFCustomize/index2.jsp");
rd.include(request, response); // or rd.forward(request, response);
// to JSP -
MBA_DB_VALIDATE : <%= request.getAttribute("MBA_DB_VALIDATE") %>
</br>
YF_DB_VALIDATE : <%= request.getAttribute("YF_DB_VALIDATE") %>
</br>
回答by agassner
You can read the URL parameters with pure client side JavaScript too, e.g. on page load. So you don't need a servlet for that.
您也可以使用纯客户端 JavaScript 读取 URL 参数,例如在页面加载时。因此,您不需要为此使用 servlet。
function getParameterByName(name) {
name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Usage (e.g. when DOM loaded):
用法(例如加载 DOM 时):
var prodId = getParameterByName('prodId');
But when you really need a servlet to pass the parameters, the first answer is the right way. Alternatively you could use AJAX to communicate with the server. Probably this is the best way to go for a JavaScript game.
但是当你真的需要一个servlet来传递参数时,第一个答案就是正确的方法。或者,您可以使用 AJAX 与服务器进行通信。这可能是 JavaScript 游戏的最佳方式。