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

  • SEARCH
  • Home
  • 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 9203787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:33:02+00:00 2026-06-17T23:33:02+00:00

Maybe I do not understand the servlet lifecycle very well, but this is what

  • 0

Maybe I do not understand the servlet lifecycle very well, but this is what i want:
I want to display a page generated by a servlet let’s say servlet: paginaAmd.
On this page I want to display a list of images stored in folder on web server.
The address of url of the images is something like:
/img/80-80-1-1-1-1-1-1-1-1-1
where /img/* is my servlet for displaying images.

All works well if I want to display one image at a time in browser.
But when I want to put all the list at once, the images are not displayed correctly. Sometimes are not displayed at all, sometimes are displayed in wrong position (the position does not alter in time), and sometimes are displayed only some images.

I suspect that somehow not all the doGet() methods are catched.

Can someone give me some advice?
Here are the servlet code witch is implemented by the tutorial here: http://balusc.blogspot.fr/2007/04/imageservlet.html

@WebServlet(name = "ImgDisplay", urlPatterns = {"/img/*"})
public class ImgDisplay extends HttpServlet
{
    private SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
    private Query query;
    private String mesajEroare = "";
    private HttpServletRequest _request;
    private HttpServletResponse _response;

    private int width = 0;
    private int height = 0;
    private int idImagine = 0;
    private int format = 0;
    private String titluArticol = "";
    private String numeImagine = "";
    private boolean imgValida = false;

    private int DEFAULT_BUFFER_SIZE = 1024 * 100;

    String fileUploadPath = "";


    @Override
    public void init() throws ServletException {
    }



    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        this._request = request;
        this._response = response;


        this.SetVariabile();

        if(imgValida)
        {
            String nImagine = this.GetImageFromDisk();
            this.DisplayImage(nImagine);
        }

    }








    private void SetVariabile()
    {
        String reqUrl = _request.getRequestURL().toString();

        String aUrl[] = reqUrl.split("/");
        String urlImg = aUrl[aUrl.length - 1];

        aUrl = urlImg.split("-");
        try
        {
            this.width = Integer.parseInt(aUrl[0]);
            this.height = Integer.parseInt(aUrl[1]);
            this.idImagine = Integer.parseInt(aUrl[2]);
            this.format = Integer.parseInt(aUrl[3]);
            this.numeImagine = aUrl[aUrl.length - 1];
            this.imgValida = true;
        }
        catch(Exception e)
        {
            this.imgValida = false;
        }

    }




    private String GetImageFromDisk()
    {
        String nImagine;
        //preiau imaginea
        PaginiImagini pa = new PaginiImagini();
        Session session;
        try
        {
            session = sessionfactory.openSession();
            session.beginTransaction();

            query = session.getNamedQuery("PaginiImagini.findByImagineID");
            query.setInteger("imagineID", this.idImagine);
            pa = (PaginiImagini) query.uniqueResult();
            session.getTransaction().commit();
            session.close();
        }
        catch( Exception e )
        {
            this.mesajEroare = "Nu pot citi din baza de date!";
        }

        // citesc imagine de pe disk
        ServletContext sctx = getServletContext();
        this.fileUploadPath = sctx.getInitParameter("file-upload-path");
        String pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMici;
        if(this.width > Setari.wImagineMica || this.height > Setari.hImagineMica)
        {
            pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMari;
        }

        nImagine =  pathImagine + "/" + pa.getNumeImaginePeDisc();
        return nImagine;
    }






    private void DisplayImage(String imageToRead) throws FileNotFoundException, IOException
    {
        File image = new File(imageToRead);

        String contentType = getServletContext().getMimeType(image.getName());
        _response.setContentType(contentType);
        _response.setHeader("Content-Length", String.valueOf(image.length()));
        _response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
        _response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        _response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        _response.setDateHeader("Expires", 0); // Proxies.

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try
        {
            // Open streams.
            input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(_response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0)
            {
                output.write(buffer, 0, length);
            }
        }
        finally
        {
            // Gently close streams.
            close(output);
            close(input);
        }

    }





    /**
     *
     * @param resource
     */
    private static void close(Closeable resource)
    {
        if (resource != null)
        {
            try
            {
                resource.close();
            }
            catch (IOException e)
            {
                // Do your thing with the exception. Print it, log it or mail
                // it.
                //e.printStackTrace();
            }
        }
    }



}
  • 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-17T23:33:03+00:00Added an answer on June 17, 2026 at 11:33 pm

    You have serious concurrency issues in your servlet. A single instance of the servlet is used to serve all the requests to this servlet. So a servlet should be stateless. But the first thing you’re doing is

    this._request = request;
    this._response = response;
    

    This means that if two concurrent requests are made to the servlet, you might have the first one set these two instance variables, then the second one resetting the same instance variables. The first image would thus be sent as a response to the second request, and nothing would be sent as a response to the first request. And this is only one of the strange things that could happen. You could also have exceptions and inconsistent data.

    Don’t store the request and response (and any other state) in instance variables. Pass them from method to method. I’ve not analyzed the whole code, but the only instance field that you should have in the servlet is sessionFactory field.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Maybe it's not worth worrying about in this scenario, but lets say you have
all. Maybe i've not googled enough, but i can't find any example on this
Maybe I am completely blind or stupid but I do not understand how I
Not that it matters strictly, and maybe I just don't yet fully understand how
I know there is a lot of controversy (maybe not controversy, but arguments at
Im having issues getting this to work, maybe its not even possible? I have
Introspection tells me that django fields have a hidden_widget attribute. Maybe its not this
Maybe I'm not searching correctly, but I can't find out how to configure the
maybe it's not so proper to ask this question here... anyway, I'm trying to
I guess my questions are not well described. Is this coding style (like the

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.