Tips for utilizing GSON and showcasing data in a JSP document

I am in the process of building a web application using JSP. One of the servlet classes I have created is as follows:

package managesystem;

import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class getUsernamesServlet extends HttpServlet{

/**
 * 
 */
private static final long serialVersionUID = 1L;

   public void doGet(HttpServletRequest req, HttpServletResponse resp){
      List<String> usernamesList = StudentManager.findAllUsernames();
      req.setAttribute("usernames", new Gson().toJson(usernamesList));

   }

}

My query pertains to how I can use Ajax to verify the availability of a username (checking against the list) and display JSON data written by the servlet in a file like register.jsp. Any guidance on this topic would be greatly appreciated.

Warm regards,

h4

Answer №1

It is recommended to write the response to the body instead of setting it as a request attribute.

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(usernamesList));

This approach allows the Ajax request on this servlet to receive a JSON response that can be easily manipulated using JavaScript.

If the goal is simply to check the availability of a username, there is an alternative method. Instead of sending the entire list of usernames to the client and performing the check in JavaScript, you can send the entered username to the servlet as a parameter. Then, let the database handle the check and return a boolean value indicating whether the username is available or not. For example:

String username = request.getParameter("username");
boolean usernameAvailable = studentService.usernameAvailable(username);

Map<String, Object> data = new HashMap<String, Object>();
data.put("usernameAvailable", usernameAvailable);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));

Using this method:

$.get('someservlet', { 'username': username }, function(data) {
    if (!data.usernameAvailable) {
        $('#somemessage').text('Username is not available, please choose another').show();
    }
});

By adopting this approach, you can conserve bandwidth and reduce the risk of exposing sensitive information.

For more information, visit:

  • How to use Servlets and Ajax?

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

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

How can I display the Facebook "feed" pop up in a jQuery dialog box?

Is there a method to display the Facebook feed pop-up (that posts to your wall) inside a jQuery dialog box? The code I currently have opens the dialog box and feed as separate pop-ups: <script> $(function() { $( "#dialog-modal" ).dialog({autoOpen: ...

Error in Swift: JSON Decoder Type Mismatch

Encountering an issue while trying to decode JSON data, resulting in the following error: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1972", intValue: 1972), CodingKeys(stringValue: "s ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

No data returned from Ajax request

I am using jQuery serialize and Ajax to capture form values and process them with JSON as the data type, but I am not getting any values returned. I have tried different approaches to troubleshoot this issue, but so far I haven't been successful. Ther ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

What is the best way to separate a JSON response into different sections based on the value of the name field?

Hello, I am currently making an API call to the Myfxbook API and receiving a JSON response with a large amount of data. Is it possible to break down this extensive response into multiple smaller parts based on the 'name' value? Here is a snippet ...

SCRIPT438: The operation failed because the object does not have the ability to use the 'forEach' property or method

Issue with IE8: Property or method 'forEach' not supported $('.tabs').tabs(); $('#search-consumables [data-ajax-call]').change(function() { var $this = $(this), settings = $this.data(), $target = $(setti ...

How to overcome Django's QueryDict List limitations

Is there a way to send data from a webpage to a django view for serialization into JSON without using QueryDict? I prefer to use simplejson to read the request, flatten it, and save the data to the database. How can I format the data so that simplejson can ...

Creating a series of promises in a structured chain

How can the code structure be improved, especially regarding exception handling within a "promise chain"? $("#save").click(function(e) { e.preventDefault(); let $self = $(this); let profile = {} $self.prop("disabled" ...

Creating a diagonal effect on a table using jQuery

I am interested in adding a diagonal effect to my table. For instance, if I have a 5x5 table, I want to highlight the first row and set the background color of the corresponding column in that row to red. The same should be done for each subsequent row. ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format. app/controllers/rando ...

Using jQuery and AJAX to dynamically add data to POST parameters

Hello, I have a question that may sound like one from a newbie. I am trying to figure out how to insert a variable into a parameter for a POST request instead of simply writing the number in directly: var x = 3; id=(the var x needs to be here)&appid=4 ...

Struggling to transfer information from a JSON document to a MYSQL database using PHP, however, it seems the data isn't aligning with the required format

Currently facing an issue with inserting JSON data into MYSQL database using PHP. The data is not aligning properly with the codes written. Extracted raw data from a transportation website: "d": [ { "CreateDate": "/Date(1465439077603)/", ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Struggling to showcase JSON information, encountering a JSON Parsing issue

I'm currently facing an issue with displaying JSON data on my screen, specifically the integer 4. Unfortunately, I keep encountering a JSON Parse Error whenever I try to retrieve and show the data. Even though the data appears to be successfully pos ...

Retrieve the HTML content of all children except for a specific child element in jQuery

Is there a way to utilize jQuery/Javascript for selecting the HTML content of the two <p> elements in the initial <div class="description? I'm open to using Regex as well. This specific jQuery selection is being executed within Node.js on a c ...

What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons. const url = 'http://newsapi.org/v2/everything?' + 'q=platformer&' + 'apiKey=3ce15c4d1fd3485cbcf17879bab498db'; ...