Within my .JSP file, I have the following HTML and JavaScript code:
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="submit" onclick="submitform()">
</form>
<p id="result"></p>
</body>
The corresponding JavaScript function is as follows:
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
};
In addition to this, a new class named User.java was created with relevant data. Subsequently, in the Jsoncontent.java file, within the POST method, variables were set up and a request was made for JSON data like so:
String jsonData = request.getParameter("per");
System.out.println(jsonData);
Gson gson = new Gson();
User data = gson.fromJson(jsonData, User.class);
System.out.println("Fetching json object");
String name = data.getName();
String address = data.getAddress();
System.out.println("User Name: "+ name );
System.out.println("User Address: "+ address );
User user = new User();
user.setName(name);
user.setAddress(address);
String jsonObj = gson.toJson(user);
System.out.println(jsonObj);
out.print(jsonObj);
Despite the lack of errors or warnings, the issue arises when clicking the submit button as the expected result is not displayed. The reason behind this unexpected behavior remains unclear.