0 Replies - 627 Views - Last Post: 05 August 2017 - 01:01 AM

#1 roparzhhemon  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 06-December 15

Servlet behaving differently in different projects

Posted 05 August 2017 - 01:01 AM

Servlet behaving differently in two different projects (NullPointerException raised)

I have an "Uploader" servlet with its associated jsp file, which I use in two different
projects. The contents of the two uploader.jsp files in each project are fully identical,
while the contents of the two Uploader.java files are identical except for the first line
(which consists of `package com.project_name_here.servlets;`).

In the first project the Uploader servlet works fine, and files are correctly uploaded. In the
second project however, when the file has been chosen for upload and the "Send" button is clicked,
for some reason when the page is reloaded it has forgotten everything about the file that was to be downloaded,
so `request.getPart("fichier");` returns `null`, which later raises a `java.lang.NullPointerException`.

The full error message is :

java.lang.NullPointerException
	com.subtitler.servlets.Uploader.getNomFichier(Uploader.java:90)
	com.subtitler.servlets.Uploader.doPost(Uploader.java:47)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)



Contents of uploader.jsp file :

<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
   
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>This will upload files</title>
</head>
<body>
    <c:if test="${ !empty fichier }">
    	<p>
    	   <c:out value="Le fichier ${ fichier } (${ description }) a été uploadé !" />
    	</p>
    </c:if>
    <form method="post" action="uploader" enctype="multipart/form-data">
        <p>
            <label for="description">Description du fichier : </label>
            <input type="text" name="description" id="description" />
        </p>
        <p>
            <label for="fichier">Fichier à envoyer : </label>
            <input type="file" name="fichier" id="fichier" />
        </p>
        <input type="submit" />
    </form>

    

</body>

</html>


Contents of Uploader.java file :
package com.subtitler.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;



/**
 * Servlet implementation class Uploader
 */
@WebServlet("/Uploader")
public class Uploader extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public static final int TAILLE_TAMPON = 10240;
    public static final String CHEMIN_FICHIERS = "/Users/ewandelanoy/Documents/Giulio/"; // A changer
    
       
    public Uploader() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.getServletContext().getRequestDispatcher("/WEB-INF/uploader.jsp").forward(request, response);
    }

    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        // On récupère le champ description comme d'habitude
        String description = request.getParameter("description");
        request.setAttribute("description", description );

        // On récupère le champ du fichier
        Part part = request.getPart("fichier");
            
        // On vérifie qu'on a bien reçu un fichier
        String nomFichier = getNomFichier(part);

        // Si on a bien un fichier
        if (nomFichier != null && !nomFichier.isEmpty()) {
            String nomChamp = part.getName();
            // Corrige un bug du fonctionnement d'Internet Explorer
             nomFichier = nomFichier.substring(nomFichier.lastIndexOf('/') + 1)
                    .substring(nomFichier.lastIndexOf('\\') + 1);

            // On écrit définitivement le fichier sur le disque
            ecrireFichier(part, nomFichier, CHEMIN_FICHIERS);

            request.setAttribute(nomChamp, nomFichier);
        }

        this.getServletContext().getRequestDispatcher("/WEB-INF/uploader.jsp").forward(request, response);
    }

    private void ecrireFichier( Part part, String nomFichier, String chemin ) throws IOException {
        BufferedInputStream entree = null;
        BufferedOutputStream sortie = null;
        try {
            entree = new BufferedInputStream(part.getInputStream(), TAILLE_TAMPON);
            sortie = new BufferedOutputStream(new FileOutputStream(new File(chemin + nomFichier)), TAILLE_TAMPON);

            byte[] tampon = new byte[TAILLE_TAMPON];
            int longueur;
            while ((longueur = entree.read(tampon)) > 0) {
                sortie.write(tampon, 0, longueur);
            }
        } finally {
            try {
                sortie.close();
            } catch (IOException ignore) {
            }
            try {
                entree.close();
            } catch (IOException ignore) {
            }
        }
    }
    
    private static String getNomFichier( Part part ) {
        for ( String contentDisposition : part.getHeader( "content-disposition" ).split( ";" ) ) {
            if ( contentDisposition.trim().startsWith( "filename" ) ) {
                return contentDisposition.substring( contentDisposition.indexOf( '=' ) + 1 ).trim().replace( "\"", "" );
            }
        }
        return null;
    }   
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1