What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below:

GetCurrentUserInfo.java

package servlet;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetCurrentUserInfo extends HttpServlet
{

    ServletContext contx = null;
    public void init(ServletConfig config) throws ServletException
    {
        contx = config.getServletContext();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        try
        {
            OutputStream outer = res.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outer);
            String userName = (String) req.getSession().getAttribute("username");
            oos.writeChars(userName);
            oos.flush();
            oos.close();
        }

        catch (Throwable e)
        {
            e.printStackTrace();

        }
    }
}

Calling.js

 function getUserInfo()
 {
     var userInfoHttp;
     if (window.XMLHttpRequest)
     {
         userInfoHttp = new XMLHttpRequest()
     }
     else if (window.ActiveXObject)
     {
         userInfoHttp = new ActiveXObject("Microsoft.XMLHTTP")
     }
     userInfoHttp.open("POST", "GetCurrentUserInfo", false);
     userInfoHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     userInfoHttp.onreadystatechange = function ()
     {
         if (userInfoHttp.readyState == 4)
         {
             if (userInfoHttp.status == 200)
             {
                 var res = TrimString(userInfoHttp.responseText);
                 alert(res);
             }
         }
     }
     userInfoHttp.send(null);
     isAnnotationUpdate = false;

 }

In response, I am receiving the username with additional characters like this: "ws@s.com" But my actual username is [email protected].

Answer №1

If you're experiencing encoding issues, consider these two solutions:

Firstly, utilize the OutputStreamWriter and specify the encoding

OutputStream stream = response.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
String userName=(String)req.getSession().getAttribute("username");
writer.write(userName);
writer.flush();

Ensure that your response has the appropriate encoding set

response.setCharacterEncoding("UTF-8");

For more information, check out this related article: Unexpected character when downloading file client side from a servlet

UPDATE

In addition to the above steps, remember to set the ContentType of the response Object to text/plain since you are dealing with plain text characters

response.setContentType("text/plain");

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

Can an EJS variable be transferred to an Angular ng-repeat filter?

I am currently working on a profile page where I need to display a user's name in plain text using <%= user.local.name %>. This requires querying the database through Mongoose. My issue now is figuring out how to pass that value to an Angular ng ...

Issues with posting incorrect values to ajaxurl when using jQuery's .each() function

Here is a modified version of pointer code that was originally sourced from this link. The original code was broken in the same way as shown here. I have multiple div elements on my web page that are generated using the given code snippet. Upon checking t ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Efficiently Extracting Information from JSON Objects

Currently, I am in the process of parsing a JSON file. Let's assume that the JSON data looks like this: {"data" : [ {"ID":12, country: "UK"}, {"ID":13, country: "USA"}, {"ID":14, country: "BRA"}, ]} Instead of just having three entries as show ...

Validation in JQuery Mobile is crucial for ensuring that user input is correct before submitting a

Trying to create a login page using JQuery Mobile, I implemented validation with the jQuery validation plugin and AJAX to post the data to a PHP server code if validation is successful. However, instead of functioning as intended, the code redirects back t ...

Issue with ng-repeat rendering on screen

Creating a breadcrumb has been my latest project, so I decided to develop a service specifically for this purpose. In order to display all the breadcrumbs, I utilized an ng-repeat in my HTML. Additionally, I set up an event listener for '$routeChange ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Navigating the complexities of transferring data between components

I recently started working with Angular 6 and encountered an issue while trying to share data in my project. Below is the code snippets: 1) Component Sidebar: selectedCategory(type:any) { this.loginService.categoryType = type; // need to pass this d ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what I’m aiming for: If ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

reloading a URL dynamically using an array in JavaScript

I need assistance with a Chrome extension code. The goal is to have it check the page that initially loads, and if it matches my website st.mywebsite.com, execute the specified code. Currently, it does not perform this check and runs on every loaded page ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Developing Java-based Ajax scripts

Is there a way to implement AJAX functionality in Java without actually using AJAX itself? I'm searching for a JAVA API that can achieve this. Just like we can submit data from a web page using a JAVA program, I want to handle AJAX operations through ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Changes in date format using jQuery datepicker

I am having trouble with the code below. Whenever I attempt to change the date, it switches from 15/5/2012 to 05/15/2012. <script> $(document).ready(function(){ $("#date").datepicker({ }); var myDate = new Date(); var month = myDa ...

Updating VAT amount using AJAX on Cart and Checkout pages in Woocommerce

I have a condition in my code that updates the VAT value to 0 if the condition is true. The code works well, but it requires reloading the page to reflect the updated VAT value. Is there a way to update the VAT value without needing to reload the page? Her ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...

I encountered a ReferenceError stating that the variable "html" is not defined

Recently, I delved into the world of Node.js for the first time. During my attempt to connect my index.html file, an error message stating 'ReferenceError: html is not defined' popped up. Below is the code snippet from my index.js: var http = re ...

The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here Below is my controller: class ReadCtrl constructor: (@$sco ...