3 Replies - 1025 Views - Last Post: 19 July 2012 - 05:45 PM

#1 xenoslash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 89
  • Joined: 19-August 09

Accessing the same java object upon button click

Posted 19 July 2012 - 02:24 PM

Hi, my scenario is similar to this:

In monster.jsp, I initialize a java object called Monster
<% Monster m = new Monster();%>

monster.jsp 's dynamic functionalities are handled by monster.js
so in monster.jsp, there is a line like this (nvm the syntax)
<script include monster.js>

I want to create a button in monster.jsp such that everytime the button is clicked, I make a java function call to the java object "m". For example button.onclick = (m.levelup());

Is there any way to do this?

I think I have to use ajax to call monsterlevelup.jsp, but I don't know how to pass the java variable 'm' to the jsp page.

Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Accessing the same java object upon button click

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,963
  • Joined: 08-June 10

Re: Accessing the same java object upon button click

Posted 19 July 2012 - 04:26 PM

Quote

... but I don't know how to pass the java variable 'm' to the jsp page.

The simple answer is: you can't. The web is "stateless", meaning that your server-side and client-side codes are never actually working together. The client makes a request which the server handles and returns the result to the client when it's done. At that point the server-side code is through and all the resources it used are freed.

That is, unless you actually store the resources someplace. It's possible to serialize objects into a session based storage mechanism, allow you to use it across requests. However the much simpler solution would be to build the classes so that they can be re-created and restored based on an identifier. That typically involves the use of a database to store the state of the object, so that it can be retrieved at any moment and manipulated.

Consider the example. (I don't know JSP well enough to write examples in it, so I'm using PHP. Whatever your understanding of PHP is, I hope you at least get the basic idea.)

This Player class stores player state in a JSON file, so it can load it on every request.
<?php
class Player {
	private $id;
	private $player_data;
	private $player_file;
	
	// Some getter functions.
	public function getID() {
		return $this->id;
	}
	public function getLevel() {
		return $this->player_data->level;
	}
	public function getHitPoints() {
		return $this->player_data->hit_points;
	}
	public function getLocation() {
		return $this->player_data->location;
	}
	
	// And some setter functions.
	public function setLevel($newLevel) {
		$newLevel = (int)$newLevel;
		if ($newLevel < 1 || $newLevel > 60) {
			throw new Exception("Player level must not be in the 1-60 range.");
		}
		else {
			$this->player_data->level = $newLevel;
			$this->save();
			// The "save" call, defined below, will save the current
			// state of the player to the JSON file.
		}
	}
	public function setHitPoints($hit_points) {
		$this->player_data->hit_points = (int)$hit_points;
		$this->save();
	}
	public function setLocation($location) {
		$this->player_data->location = $location;
		$this->save();
	}
	
	// A constructor to load the player data from the JSON file.
	public function __construct($player_id) {
		$player_id = (int) $player_id;
		if ($player_id === 0) {
			throw new Exception("Player ID must be a number above 0");
		}
		$this->id = $player_id;
		
		$this->player_file = "playerData/player_{$player_id}.json";
		if (!file_exists($this->player_file)) {
			throw new Exception("Player #{$player_id} does not exist.");
		}
		
		$this->player_data = json_decode(file_get_contents($this->player_file));
	}
	
	// A function that saves the state of the player to the JSON file.
	private function save() {
		$jsonData = json_encode($this->player_data);
		if ($jsonData !== false) {
			if (file_put_contents($this->player_file, $jsonData) === false) {
				throw new Exception("Failed to save player data!");
			}
		}
		else {
			throw new Exception("There's something wrong with the player data!");
		}
	}
}



This allows me to create API calls to manipulate players. Something like:
<?php
// File: setPlayerLevel.php
header("Content-type: application/json; charset=UTF-8");

require "Player.php";

if (isset($_GET['playerID'], $_GET['newLevel'])) {
	try {
		$player = new Player($_GET['playerID']);
		$player->setLevel($_GET['newLevel']);
		
		header("HTTP/1.0 200 OK");
		echo json_encode(["message" => "Success!"]);
	}
	catch (Exception $e) {
		header("HTTP/1.0 400 Bad Request");
		echo json_encode(["message" => $e->getMessage()]);
	}
}
else {
	header("HTTP/1.0 400 Bad Request");
	echo json_encode(["message" => "Invalid input data!"]);
}



Now all that the Javascript code needs to do to make use of this is to call the PHP file and pass along the player ID and the new level. Presumably the player would be logged on using another API call, so the Javascript code would have the player ID saved somewhere. - This could be achieved with a simple GET AJAX call:
var updateLevel = function(playerID, newLevel) {
	var xml = new XMLHttpRequest();
	xml.open("GET", "setPlayerLevel.php?playerID=" + playerID + "&newLevel=" + newLevel, true);
	xml.onreadystatechange = function() {
		if (xml.readyState == 4) {
			if (xml.status != 200) {
				console.log("setPlayerLevel.php returned code " + xml.status);
			}
		}
	}
	xml.send(null);
}


This would just update the level, or log an error if an invalid status code is returned. - You may want to replace that log with some more user-friendly way of displaying errors, or something.

Hope this makes sense :)
Was This Post Helpful? 2
  • +
  • -

#3 xenoslash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 89
  • Joined: 19-August 09

Re: Accessing the same java object upon button click

Posted 19 July 2012 - 04:59 PM

Oh wow. I feel so spoilt now haha. Thanks for the thorough explanation.

So from what I gather, there seems to be 2 solutions:
1. Serialize Monster java object using something like JSON, and do everything in javascript.
2. Use ajax to pass along information needed to reconstruct the new Monster, then .php (or .jsp in my case) will construct a new Monster object, and call .levelup() on it.

Sigh.. maybe I should have used a more relevant example.
So in a monster-less land, I have this java object which talks to a database. Let's call it client

Client.java
2 methods:
1. Client(String dbName) --constructor
2. void submitnewcontent(string new stuff)

in the .jsp file, I have a Client object instantiated.
<% Client c = new Client("mydb"); %>
now everytime the button is clicked, I want to call c.submitnewcontent("hiii");

In this case, the only solution I could think of is to make an ajax call to handleNewContent.jsp, and pass along "mydb" and "hiii"

then handleNewContent.jsp would have to reconstruct Client again, before calling submitNewContent("hii");
This doesn't seem like a good solution since reconstructing Client might be expensive (connecting to db, and what not).
And from your explanation (which was clear), it's not possible for me to make a call on submitNewContent on the same Client instantiation ('c') for every button click.

So.. have people always been reconstructing java object when they want to mutate/do stuff with it upon button clicks?

This post has been edited by xenoslash: 19 July 2012 - 05:01 PM

Was This Post Helpful? 0
  • +
  • -

#4 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,963
  • Joined: 08-June 10

Re: Accessing the same java object upon button click

Posted 19 July 2012 - 05:45 PM

Quote

So from what I gather, there seems to be 2 solutions:
1. Serialize Monster java object using something like JSON, and do everything in javascript.

No, the Monster object, from what I gathered, was a server-side Java object, so that is where it would have to be. The serialized object would be restored on the server-side on each request and used there. It's basically the same concept I showed you before, but instead of recreating a new object server-side, you would fetch it from some sort of session storage and decompress it back into it's original form. From Javascript's perspective there would be no difference.

This has it's challenges as well, and in my experience it's better to just recreate the object.

Quote

then handleNewContent.jsp would have to reconstruct Client again, before calling submitNewContent("hii");
This doesn't seem like a good solution since reconstructing Client might be expensive (connecting to db, and what not).

That may be true, but you have to keep in mind what type of application you are developing. Websites are not event driven like normal desktop applications. Keeping the application alive indefinitely while waiting for user input may make sense in a single user environment, but on a website you will quickly overload the server if you try to keep everything alive across requests. You have to be careful how much overhead your scripts are causing.

Talking about creating database connections... Common resources like that; once that can be reused between requests, are sometimes "pooled". It saves you having to create a new connection on each request. Instead you have your application open a number of connections when it first starts (or on demand) and then allow your request handling code to acquire an active connection from the connection pool, use it to do whatever database queries your script needs to do, and then release it back into the pool. - I'm not sure how you'd do that in JSP, but I'm sure there are ways.

Quote

So.. have people always been reconstructing java object when they want to mutate/do stuff with it upon button clicks?

I don't know about Java, but in PHP this is pretty much always done. There are ways to reduce the overhead of creating database links and such, using persistent connections or connection pooling, but in most cases even that isn't needed.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1