Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9209063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:45:15+00:00 2026-06-18T00:45:15+00:00

I am writing a software and a part of this software involves communication between

  • 0

I am writing a software and a part of this software involves communication between my Java desktop client app and a servlet. The servlet pulls out textual data from the database and writes it out in 1 single out.println() statement.
The problem is that whenever the textual data written by the servlet is much, parts of the text never make it to the client.This is despite setting the contentlength response.setContentLength(text.length()) in the servlet. What could be happening?
This is the servlet:

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;'
import javax.sql.DataSource;
/**
 *
 * @author GBEMIRO
 */

public class MessageRetrieverServlet extends HttpServlet {

DataSource pool;  // Database connection pool
private HttpSession session;

@Override
public void init() throws ServletException {
    try {
        // Create a JNDI Initial context to be able to lookup the DataSource
        InitialContext ctx = new InitialContext();
        // Lookup the DataSource, which will be backed by a pool
        //   that the application server provides.
        pool = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
        if (pool == null) {
            throw new ServletException("Unknown DataSource 'jdbc/TestDB'");
        }
    } catch (NamingException ex) {
        ex.printStackTrace();
    }
}//end method init

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    session = request.getSession();
    Connection conn = null;
    try {

        String email = request.getParameter("email");

        conn = pool.getConnection();

        PreparedStatement pstmt = conn.prepareStatement("SELECT MSG FROM POSTS_TABLE WHERE EMAIL = ? ");

        pstmt.setString(1, email);

        ResultSet rs = pstmt.executeQuery();
        rs.next();

        //The huge text
        Clob clob = rs.getClob("MSG");

        /**
         * The text retrieved into msg is very large, but I checked with
         * System.out.println(msg) statements it is complete up to this
         * point, no part of it is lost. So the retrieval from the database
         * is always successful.
         *
         */
        String msg = clob.getSubString(0, (int) clob.length());

        out.print(msg);

    }//end try
    catch (SQLException exception) {
        String errorMsg = "error3";
        exception.printStackTrace();
        out.print(errorMsg);
    } catch (NumberFormatException numberFormatException) {
        String errorMsg = "error4";
        numberFormatException.printStackTrace();
        out.print(errorMsg);
    }


    try {
    } finally {
        out.close();
        try {
            if (conn != null) {
                conn.close();
            }  // return to pool
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}//end method

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>
}

Now this is the receiving method on the client where the problem arises:

public void retrieveMessages(){
    try {
        URL url = new URL("http://"+server_name_or_ip+":8080/SecureChatEngine/MessageRetrieverServlet");

            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setDoInput(true);
        urlCon.setDoOutput(true);
              urlCon.setRequestMethod("POST");        
  urlCon.setRequestProperty("Content-type",
      "application/x-www-form-urlencoded");

  PrintWriter out = new PrintWriter( new OutputStreamWriter(
      urlCon.getOutputStream(  ), "8859_1"), true );
        StringBuilder sb = new StringBuilder("");
        sb.append(URLEncoder.encode("email","UTF-8"));
        sb.append("=");
        sb.append(URLEncoder.encode("gbenroscience@yahoo.com","UTF-8"));

           String formData = sb.toString();
           out.print(formData);
        out.flush();


   int contentLength = urlCon.getContentLength();
  byte[] raw = new byte[contentLength];
  int length = urlCon.getInputStream().read(raw);
  System.out.println("len = "+length);
  out.close();
/**
* The message retrieved here is incomplete..a truncated version of what is coming from the server, whereas 
* it should be the full version.
*/
String serverMsg = new String(raw, 0, length);    

}
catch(Exception e){
e.printStackTrace();
}

}//end method
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T00:45:17+00:00Added an answer on June 18, 2026 at 12:45 am

    @EJP’s answer is correct, you aren’t guaranteed to read the input stream with one read. You need to loop as follows…

    BufferedReader in = null;
        StringBuilder sb = new StringBuilder();
        try {
            in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            String input = null;
            while((input=in.readLine())!=null) {
                sb.append(input);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        String serverMsg = sb.toString();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing my first proper useful piece of software. Part of it will involve
I'm writing HFT trading software. I'm trying to optimize it. I figured out that
I'm writing bug tracking software in PHP, and today I saw this in another
I'm writing an OS X client for a software that is written in PHP.
I am writing this question in part based on a related question on helper-scripts
I'm a student and this is my first time writing a piece of software.
We are considering writing a software in Java that records whats monitor for certain
This is a simple question. I have been writing a software with .NET 4.5
I am writing a software tool which, as part of its main task, must
I'm writing software to simulate the first-fit memory allocation schema. Basically, I allocate a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.