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

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Having trouble getting static serving to work on Express.js when custom middleware is added

Seeking assistance with creating a middleware for my express js website to incorporate subdomains and serve static image, css, and js files. While my HTML pages load properly, I encounter long page load times and the javascript files fail to load. Any gui ...

Ensuring Smooth Transfer: Sending Local Storage Data to MVC Controller

I'm attempting to send an array of strings from my local storage (key value) to an MVC controller. Here's the code I have so far: Inside the cshtml View file: <script> function getFavouriteBooks() { var ids = JSON.par ...

Anticipating the refresh of React state in a functional component

I am looking for a way to ensure that the function handleOpen is only called after all the state variables (nameError, emailError, messageError) have been updated. The issue I am facing is that the state update is not instantaneous, causing handleOpen to s ...

Unable to switch the text option

[Fiddle] I'm currently working on a project where I want pairs of buttons to toggle text by matching data attributes. While I can successfully change the text from "Add" to "Remove" on click, I am facing an issue with toggling it back to "Add" on the ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...

Generating JSON output in PHP

I've been struggling to figure out why I can extract some parts of the JSON data but not others... Essentially, I am retrieving JSON from a URL (). In my PHP code (using Laravel5), I have the following: $url = 'https://public-crest.eveonline.co ...

Condition has been fulfilled for both ngShow and ngHide

I am attempting to show a loading icon while data is being loaded, and then display the data once it is ready. However, I am encountering a problem where for a brief moment, both the loading icon and the data are visible... Below is my code snippet: $scop ...

Master Chef crafting a lively Json document

I'm encountering an issue with generating a JSON file using a template within a Chef template. The JSON file I need to create, named plugin.json, should look like this: { "agents": [ { "name" : "sqlhost", "host" : "localhost" ...

Guide on hosting two html pages on a NodeJS server

Currently, I am in the process of learning NodeJS and Javascript with a goal to construct a basic server that can host 2 HTML pages. One page should be accessible via localhost:3000/index, while the other can be reached through localhost:3000/about. While ...

Can someone explain how I can effectively test the internal workings of a promise using Jasmine?

Within the Angular component I am testing, there is an async promise that I am struggling to examine. The code inside the 'then' block is crucial for my testing purposes, but I cannot seem to access it. angular.module('Ls', [ ]) funct ...

Using the .val method on an input element modifies the HTML content without affecting the value displayed

Currently, I am working on validating the range input type by utilizing JavaScript along with jQuery's val method. While it successfully displays the output in HTML, I encountered an issue where changes to the value are not being logged in the console ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

Verify if the user possesses legitimate Jira REST API credentials

I am currently using the npm module jira-client to send API requests to my Jira system. I need a way to verify whether the user has valid credentials before proceeding. Depending on the validation result, I plan to either: Inform the user that their use ...

What is the best location to initialize Firebase in a React Native application?

What is the best way to initialize Firebase in a React Native project and how can I ensure that it is accessible throughout the entire project? Below is my project structure for reference: Project Structure Here is a basic template for initializing Fireb ...

VBA MACRO: Attempting to modify a VBA script that generates JSON data

Below is a sample code for querying an API call and extracting specific items from JSON. However, the code currently retrieves data based on ZIP code. How can it be modified to query by state instead? Option Explicit 'Individual Public r As Long Pub ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Ways to turn off JavaScript when reaching a certain breakpoint, similar to a media query

I am facing an issue with my <header> and <nav> blocks which are impacted by JavaScript. Is there a way to create a JavaScript solution similar to a media query that would deactivate this JavaScript code if the window width is less than or equa ...