admin管理员组

文章数量:1336293

I am working on a board game with dynamic board size of 5x5,...,8x8
This should be a game that runs on a web.

I am working with NetBeans and tomcat as the server for testing.

I have the GameSettings.html which the user choose the board size and press submit.

The data is being sent to servlet named: GameSettingsServlet.java

There I pull out the boardSize and parse it to an integer:

@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.

How can I pass the boardSize to the javaScript or HTML ?

I searched on the web but I found only about JSP and I need it on HTML.

I am working on a board game with dynamic board size of 5x5,...,8x8
This should be a game that runs on a web.

I am working with NetBeans and tomcat as the server for testing.

I have the GameSettings.html which the user choose the board size and press submit.

The data is being sent to servlet named: GameSettingsServlet.java

There I pull out the boardSize and parse it to an integer:

@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.

How can I pass the boardSize to the javaScript or HTML ?

I searched on the web but I found only about JSP and I need it on HTML.

Share Improve this question asked Sep 22, 2014 at 22:02 E235E235 13.5k29 gold badges111 silver badges159 bronze badges 4
  • 2 JSP is some kind of intermediate between your java and your html. You'll get HTML from the JSP, as shown in andrex' answer. – Joel Commented Sep 22, 2014 at 22:19
  • 1 yeah, you need to use JSP. Otherwise, you could do Ajax directly to the server and get what you want that way. After the servlet does it work, where does the request end up being rendered? – mtyson Commented Sep 22, 2014 at 22:22
  • 1 Actually, since it's for a video game, the ajax alternative is probably better than going through a JSP and full page reload. Eviatar, you'll probably don't want to reload your full gameboard display each time a modification is made, right? In this case you should look at ajax requests. – Joel Commented Sep 22, 2014 at 22:28
  • 1 Without jsp you can use ajax is right. I update my answer to include a way of returning a value to an ajax request. It's not a plete code but that should get you started. – andrex Commented Sep 22, 2014 at 22:49
Add a ment  | 

3 Answers 3

Reset to default 3

In your servlet you go like this

request.setAttribute("boardsize" boardSize);

Thats the name of the atrribute and the variable.

The in the jsp page you go

<% int boardSize = (Integer) request.getAttribute("boardsize"); %>

Then when you are going to use it in javasceipt you do it like this

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

You can start from here http://docs.oracle./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.

As per the ments 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.

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.

The below given code can serve the response from JSP to Servlet . //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 . //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, e.g. on page load. So you don't need a servlet for that.

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):

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 municate with the server. Probably this is the best way to go for a JavaScript game.

本文标签: javaHow to pass parameters from servlet to JavaScriptStack Overflow