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

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

Utilizing the <webview> functions within Electron: A comprehensive guide

After checking out the documentation for the Electron <webview>, I attempted to use some of the listed methods with no success. In inspecting the properties of the <webview> element, I found that its prototype is labeled as webview (__proto__ : ...

Challenges with cross domain iframes

I am trying to find a way to send a message from an iframe to the parent page at regular intervals, for example: Iframe Domain = www.abc.com Parent Domain = www.xyz.com I have looked into the following resources: Cross domain iframe issue If anyone ha ...

updating a d3js line graph in real-time using JSON information

Trying to wrap my head around dynamically updating a line graph with new data, shifting the graph to the left and adding fresh data from the right - you following me? Want it to behave just like the examples on I'm fairly new to d3 (javascript) and l ...

Ways to designate ROLES within the _user database on Cloudant

I am struggling to figure out how to add Roles to users in the Cloudant user database (_users). Despite searching through Google and Cloudant Docs, I have not been able to find a solution. There is mention of a Cloudant _user db, but I can't seem to u ...

Disable location prompt feature when using AngularJS with Maps API

For my web application, I developed a feature that includes a map with custom markers using Angular loops: <map data-ng-model="mymap" zoom="4" center="[38.50, -95.00]" style="heigth:375px"> <div ng-repeat="item in list"> <marker pos ...

Error encountered: JSON data contains an unexpected character at line 1, column 2

One of my PHP scripts looks like this: $STL = array(); $filter = array(); $filter['sort_by'] = "date_added"; $filter['sale'] = "F"; $filter['per_page'] = "12"; $STL['filter'] = $filter; echo json_encode($STL); When ...

Tips for accessing hidden field values in a second jsp page

I have a webpage called page1.jsp where I am including hidden fields. Here is the code snippet: <form action = "page2.jsp" method = "post" id = "hiddenValuesForm"> <input type = "hidden" name = "userData" value="" id = "useDataID"> <input t ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

verifying the AJAX validation request URL

I am seeking a way to ensure that the valuable data generated by my ajax code on my webpage can only be accessed when the request originates from my site. This will prevent third parties from using the data without permission. I intend to implement this ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Unable to substitute 'npm run build' for 'webpack' command

I'm having trouble with npm run build not calling webpack as expected. I've modified the script in my package.json file, but it didn't work. I'm using Linux. Here is a snippet from my package.json file: { "name": "learn-webpack", ...

What is the purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

embedding a button alongside the pager in an HTML document

I am encountering an issue with the positioning of a button in my paginated table setup. The button is currently displaying below the pager instead of being aligned on the left side of the page along with the pager. https://i.stack.imgur.com/gUiB9.png To ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Modifying the appearance of Bootstrap button colors

I recently came across this code on the Bootstrap website. I am curious about how to change the text color from blue to black in this specific code snippet. Currently, the text is appearing as blue by default. For reference and a live example, you can vis ...

"Failed authentication for client" in the testing environment of PayPal sandbox

I obtained the code from github and updated the Client ID & App Secret accordingly. It worked flawlessly. https://github.com/paypal-examples/docs-examples/tree/main/advanced-integration However, upon integrating the codes into my project, I encountered th ...

Ways to extract metadata from a given URL

Recently, I've delved into the world of JavaScript and I'm looking to extract metadata from a given URL. Whenever a URL is entered into an input field, I want to retrieve its meta data - a simple task in HTML using JavaScript. However, every time ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...