简体   繁体   中英

How to pass parameters from servlet to JavaScript

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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