Guide on sending JSON data to a server and receiving JSON/XML in response with JSP

I am new to developing web applications. I have successfully created a dynamic web project using Java EE on a Glassfish server. Now, I am trying to enable clients to send data to the server using JSON and receive data from the server in either JSON or XML format. Although I have grasped the server-side programming concepts through online research, I am facing difficulties implementing the code. Currently, I am using AJAX to send JSON data from the client side. However, I seem to be missing some code for the server side. My plan is to use JSP to read the JSON data, utilize a bean that generates data, and send the processed data back to the client. Below is a snippet of my code, but I am uncertain about its functionality. Any advice would be highly appreciated as I value your assistance!

Below is the AJAX code used on the client side to send two input numbers from a form:

$(function() {
    $("#myform").submit(function() {
        var lat = $("#num1").val();
        var lon = $("#num2").val();
        alert("form");

        if (num1 == '' || num2 == '') {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        } else {
            $.ajax({
                type : "POST",
                url : "marker.jsp",
                contenttype : 'application/json; charset=utf-8',
                data : {
                    "num1" : "wtf",
                    "num2" : $("#num2").val(),
                },

                success : function(msg) {
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                    alert(msg);

                }
            });
        }

        return false;
    });
});

Upon accessing the JSP page, I noticed that only null values are displayed. Here's a snippet of the server-side code where I intended to send XML data initially. I am unsure if the request.getParameter method functions correctly and how to send the data back using XML or JSON format. Your guidance on this matter is greatly appreciated!

<?xml version="1.0" encoding="UTF-8"?>
<%@ page contentType="text/xml" %>
<%@ page             import="javax.naming.InitialContext,net.roseindia.ejb3.stateless.*,javax.ejb.EJB,java.util.*"%>

...server-side script continues here...

Answer №1

If you're not currently utilizing an MVC framework, I highly recommend incorporating one into your development process. Rendering XML/JSON from a JSP can lead to cumbersome code that may not be the most efficient or valid.

Consider adopting a robust MVC framework like VRaptor, which simplifies the creation of RESTful web applications with ease. By leveraging VRaptor and its integration with XStream Framework, responding to requests with JSON objects becomes straightforward. Check out how easy it is to achieve this:

    import static br.com.caelum.vraptor.view.Results.*;

    @Resource
    public class ClientsController {

    private final Result result;
    private final ClientDao dao;

    //result and dao parameters are automatically injected by VRaptor, allowing for flexibility with Dependency Injection frameworks
    public ClientsController(Result result, ClientDao dao) {
        this.result = result;
        this.dao = dao;
    }

    @Get("/client/json")
    public void loadJson(MyParam param) {
        result.use(json()).from(dao.getClient(param.id)).serialize();
    }

    @Get("/client/xml")
    public void loadXml(MyParam param) { 
        result.use(xml()).from(dao.getClient(param.id)).serialize();
    }
}

With Vraptor, deserializing objects from JSON and injecting them into controller actions is seamlessly integrated into your workflow!

For more information and examples, visit this page!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Could offering a Promise as a module's export be considered a legitimate approach for asynchronous initialization in a Node.js environment?

I am in the process of developing modules that will load data once and create an interface for accessing that data. I am interested in implementing asynchronous loading of the data, especially since my application already utilizes promises. Is it considere ...

Importing XML data into a JavaScript variable using jQuery without displaying an alert message

Despite previously asking questions about loading XML into a JS variable, I haven't found a satisfactory solution. In my script, I declare a variable before making an ajax request and then assign the result to that variable. However, this only seems t ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

Display a specific division depending on the outcome of an Ajax request within a PHP form

My PHP form has a layout similar to this: <form> <div id="inid"> National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" /> </div> <hr /> name: <div id="individua ...

After clicking, revert back to the starting position

Hey there, I have a question about manipulating elements in the DOM. Here's the scenario: when I click a button, a div is displayed. After 2 seconds, this div is replaced by another one which has a function attached to it that removes the div again. ...

Oops! The angular app encountered an error: TypeError - it cannot read property '0' of undefined. Time to debug

Having difficulty grasping the source of an error, as the html side is able to read list[3].main.temp without any issues. However, in the second loop of the generateList function, I encounter an error specifically on $scope.list[i].main.temp, which throws: ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

Why does React component still use old state when re-rendering?

I recently encountered an issue with my code. I am using an array of objects in my state, and when I delete an item from the array, the component does not render correctly without the deleted object. Additionally, when I try to open another object (trigger ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...

Instructions for transferring a JavaScript array to a Java servlet

Greetings everyone! I am currently working on a web application with an orthodox approach, utilizing AJAX in Java and JavaScript. I am wondering if it is feasible to pass an array from JavaScript to a Servlet. ...

Guide on configuring and executing AngularJS Protractor tests using Jenkins

I am encountering an error with the following configuration: ERROR registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX 18:17:05.892 INFO ...

Utilize GSON to encode a collection of objects in a map and ensure the preservation of type

In my coding project, I have defined a class as follows: public class MyClass { private final Map<Property, Object> properties; } The type Property is actually an enum. Imagine that the properties attribute contains two elements: one with a v ...