简体   繁体   English

如何将参数从servlet传递到JavaScript

[英]How to pass parameters from servlet to JavaScript

I am working on a board game with dynamic board size of 5x5,...,8x8 我正在做一个棋盘游戏,动态棋盘大小为5x5,...,8x8
This should be a game that runs on a web. 这应该是在网络上运行的游戏。

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上的信息。

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. 根据注释所指出的,还有一种做ajax的方法,如果您使用ajax请求,则servlet可以返回值。 You do need a response to do this. 您确实需要响应才能执行此操作。

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. 我敢打赌,当您阅读有关Java,Servlet,JSP的更多信息时,您将学到更多。 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. 只需花更多的精力在阅读上,这样您就可以了解它并不难理解,但是如果您发现这样做有困难,请耐心等待。

The below given code can serve the response from JSP to Servlet . 以下给出的代码可以满足JSP对Servlet的响应。 //setParameter -- getparameter // setParameter-getparameter

// 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 . 下面给出的代码可以满足Servlet对JSP的响应。 //setAttribute -- getAttribute // setAttribute-getAttribute

   // 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>

You can read the URL parameters with pure client side JavaScript too, eg on page load. 您也可以使用纯客户端JavaScript读取URL参数,例如在页面加载时。 So you don't need a servlet for that. 因此,您不需要一个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 (eg 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. 但是,当您确实需要servlet传递参数时,第一个答案就是正确的方法。 Alternatively you could use AJAX to communicate with the server. 或者,您可以使用AJAX与服务器通信。 Probably this is the best way to go for a JavaScript game. 也许这是开发JavaScript游戏的最佳方法。

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

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