Home > Back-end >  Getting User input from the web into a java program? [closed]
Getting User input from the web into a java program? [closed]

Time:09-29

How do I go about setting a Java object's property via user input from the web? Like, I want to be able to enter playerOne's and playerTwo's "health" from a website, I know how to do that via command-line (with Scanner object) but how do I "scan" from an HTML page's user input field? Do I have to use JSP or something like that?

static void playGame() {

    Person playerOne = new Seller();
    Person playerTwo = new Buyer();
    playerOne.setHealth(100); // I want this 100 to come from user input on an html page
    playerTwo.setHealth(500); // I want this 500 to come from user input on an html page
    System.out.println("playerOne's health is "   playerOne.getHealth());
    System.out.println("playerTwo's health is "   playerTwo.getHealth());
    
    //.... more code here
}

CodePudding user response:

Its not possible in pure java. But using https://www.webswing.org/ It is possible.

First make a server program for your game.

Then Make a client program for your game.

Then convert it it into html using https://www.webswing.org/

Then run server first and then run client.....

CodePudding user response:

You will need to send a request to the server where you want to extract data from. There are many ways to send a request via Java. Example request:

// Create a neat value object to hold the URL
URL url = new URL("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");

// Open a connection(?) on the URL(??) and cast the response(???)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Now it's "open", we can set the request method, headers etc.
connection.setRequestProperty("accept", "application/json");

// This line makes the request
InputStream responseStream = connection.getInputStream();

// Manually converting the response body InputStream to APOD using Jackson
ObjectMapper mapper = new ObjectMapper();
APOD apod = mapper.readValue(responseStream, APOD.class);

// Finally we have the response
System.out.println(apod.title);

Taken from https://www.twilio.com/blog/5-ways-to-make-http-requests-in-java

I advise you to read the whole article. First thing's first. Implement some dummy request sending that actually works.

When that's done, read about API in general, if the website's data is to be requested via an API. If it's displayed via an HTML page, then you will need to download the HTML and mine the information you need from that. For that purpose, you will need an HTML parser. So, once you know how a request is to be sent, you need to send specifically the request that you actually need and parse the response appropriately. Once you are able both to send a request and to parse the response of the resource you are interested about, figure out what you intend to do with the received data.

  • Related