Hey Friends,

Developing an Online Shopping System.

Firstly had posted a code regarding MD5 Encryption and it was solved very quickly.

Require the same help again.

While registering an image selected by the User should be inserted into the Database.

Posting a Code which follows the DAO Pattern but i don't know what to insert in the Method to allow it to insert the image into the database.

Thanking You all in advance

    public void AddUser(String UserID , String FirstName , String MiddleName , String LastName , String Age , String MobileNumber , String Gender , String City , String EMail , String Username , String Password , String HashWord , String FileName)
            throws ClassNotFoundException , SQLException , NoSuchAlgorithmException , FileNotFoundException
    {
        try
        {


            MessageDigest md5 = MessageDigest.getInstance("MD5");

            md5.update(Password.getBytes());

            BigInteger Hash = new BigInteger(1 , md5.digest());

            HashWord = Hash.toString(16);

            Statement myStatement = ConnectToDatabase();

            String SQLQuery = "INSERT INTO Users(FirstName , MiddleName , LastName , Age , MobileNumber , Gender , City , EMail , Username , HashWord , User_Image) VALUES ('" + FirstName + "' , '" + MiddleName + "' , '" + LastName + "' , '" + Age +"' , '" + MobileNumber + "' , '" + Gender +"' , '" + City + "' , '" + EMail + "' , '" + Username + "' , '" + HashWord + "' , '" + FileName + "')";

            myStatement.executeUpdate(SQLQuery);


        }

        catch (ClassNotFoundException CNFE)
        {
            System.out.println(CNFE);

            throw CNFE;
        }

        catch (SQLException SQLE)
        {
            System.out.println(SQLE);

            throw SQLE;
        }

        catch (NoSuchAlgorithmException NSAE)
        {
            System.out.println(NSAE);

            throw NSAE;
        }

    }

Registration Servlet

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Users;

import DataAccessObject.DAO;
import DataAccessObject.DAO_Interface;
import com.oreilly.servlet.MultipartRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author SaguWesker
 */
public class Registration extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        try 

        {
            RequestDispatcher rd = request.getRequestDispatcher("Relay");            

            DAO_Interface Dao = DAO.getDAOInterface();

            Dao.AddUser

                    (

                    request.getParameter(""),

                    request.getParameter("FirstName"), 

                    request.getParameter("MiddleName"), 

                    request.getParameter("LastName"), 

                    request.getParameter("Age"), 

                    request.getParameter("MobileNumber"), 

                    request.getParameter("Gender"), 

                    request.getParameter("City"), 

                    request.getParameter("EMail"), 

                    request.getParameter("Username"),

                    request.getParameter(""),

                    request.getParameter("HashWord"), 

                    request.getParameter("FileName"));

            HttpSession Session = request.getSession();

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

            Session.setAttribute("FirstName", FirstName);

            RequestDispatcher view = request.getRequestDispatcher("registration_complete.jsp");

            view.forward(request, response);
        }

        catch (ClassNotFoundException CNFE)
        {
            System.out.println(CNFE);
        }

        catch (SQLException SQLE)
        {
            System.out.println(SQLE);
        }

        catch (NoSuchAlgorithmException NSAE)
        {
            System.out.println(NSAE);
        }

        finally 

        {            
            out.close();
        }
    }

    // <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>
}

Hey Friends,

Have made great progress in the code.

Getting the Null Pointer Exception error

All Help Appreciated

public void AddUser(String UserID , String FirstName , String MiddleName , String LastName , String Age , String MobileNumber , String Gender , String City , String EMail , String Username , String Password , String HashWord , FileInputStream FIN , String File_Path , File Image_File)
            throws ClassNotFoundException , SQLException , NoSuchAlgorithmException , FileNotFoundException
    {
        try
        {

            MessageDigest md5 = MessageDigest.getInstance("MD5");

            md5.update(Password.getBytes());

            BigInteger Hash = new BigInteger(1 , md5.digest());

            HashWord = Hash.toString(16);

            Statement myStatement = ConnectToDatabase();

            String SQLQuery = "INSERT INTO Users(FirstName , MiddleName , LastName , Age , MobileNumber , Gender , City , EMail , Username , HashWord , User_Image , Image_Name , Image_Length) VALUES ('" + FirstName + "' , '" + MiddleName + "' , '" + LastName + "' , '" + Age +"' , '" + MobileNumber + "' , '" + Gender +"' , '" + City + "' , '" + EMail + "' , '" + Username + "' , '" + HashWord + "' , '" + FIN + "' , '" + File_Path +"' , '" + Image_File + "')";

            myStatement.executeUpdate(SQLQuery);


        }

        catch (ClassNotFoundException CNFE)
        {
            System.out.println(CNFE);

            throw CNFE;
        }

        catch (SQLException SQLE)
        {
            System.out.println(SQLE);

            throw SQLE;
        }

        catch (NoSuchAlgorithmException NSAE)
        {
            System.out.println(NSAE);

            throw NSAE;
        }

    }

Registration Method

public class Registration extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        //String FileName = "";

        try 

        {
            //MultipartRequest Multi = new MultipartRequest(request, ".", 5*1024*1024);

            //Enumeration Files = Multi.getFileNames();

            //File F = null;

            //while (Files.hasMoreElements())

            //{

                //String name = (String)Files.nextElement();

                //FileName = Multi.getFilesystemName(name);

                //String Type = Multi.getContentType(name);

                //F = Multi.getFile(name);

                //System.out.println("File Detail is" + F);

            //}

            //InputStream IS = new FileInputStream(F);

            //byte b[] = new byte[IS.available()];

            //IS.read(b);

            String StringPath = request.getParameter("Image");

            String File_Path = StringPath.substring(StringPath.lastIndexOf(""));

            File Image_File = new File(StringPath);

            FileInputStream FIN = new FileInputStream(Image_File);

            RequestDispatcher rd = request.getRequestDispatcher("Relay");            

            DAO_Interface Dao = DAO.getDAOInterface();

            Dao.AddUser(

                    request.getParameter(""), 

                    request.getParameter("FirstName"), 

                    request.getParameter("MiddleName"), 

                    request.getParameter("LastName"), 

                    request.getParameter("Age"), 

                    request.getParameter("MobileNumber"), 

                    request.getParameter("Gender"), 

                    request.getParameter("City"), 

                    request.getParameter("EMail"), 

                    request.getParameter("Username"),

                    request.getParameter(""),

                    request.getParameter("HashWord"), 

                    FIN,

                    File_Path,

                    Image_File);

            HttpSession Session = request.getSession();

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

            Session.setAttribute("FirstName", FirstName);

            RequestDispatcher view = request.getRequestDispatcher("registration_complete.jsp");

            view.forward(request, response);
        }

        catch (ClassNotFoundException CNFE)
        {
            System.out.println(CNFE);
        }

        catch (SQLException SQLE)
        {
            System.out.println(SQLE);
        }

        catch (NoSuchAlgorithmException NSAE)
        {
            System.out.println(NSAE);
        }

        finally 

        {            
            out.close();
        }
    }

Hy Friends, Please Assist i am in need of big help and advice.

I Have managed to get this far without DAO pattern.

The Same Problem is coming and it does not show where the NullPointer Exception is coming from.

INFO  [STDOUT] java.lang.NullPointerException

Trial.java

public class Trial extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
              String strpath=request.getParameter("Image");
              String filepath=strpath.substring(strpath.lastIndexOf("\\")+1);
              File imgfile = new File(strpath);
              FileInputStream fin = new FileInputStream(imgfile);
              Connection con = null;
              Class.forName("com.mysql.jdbc.Driver").newInstance();
              con = DriverManager.getConnection("jdbc:mysql://localhost:3306/iCorp","root","");
              PreparedStatement pre = (PreparedStatement) con.prepareStatement("insert into user_profile_image(image,image_name,image_length) values(?,?,?)");
              pre.setBinaryStream(1,fin,(int)imgfile.length());
              pre.setString(2,filepath);
              pre.setLong(3,imgfile.length());
              pre.executeUpdate();
              pre.close();
              String L_url1=response.encodeRedirectURL("myUpload.jsp");
              response.sendRedirect(L_url1);
}




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

finally {            
            out.close();
        }
    }

JSP Page for upload

<form name="Upload_Image_Form" method="post" action="Relay" enctype="multipart/form-data">   

<table align="center" border="1" cellspacing="1px" style="width: auto; border-radius:3px; border-style: solid">

<tr>

<td>

<label style="font-family: Trebuchet MS; font-size: large ">Password</label>    

</td>

<td>

<input type="file" name="Image" value="" id="menu_button"/>    

</td>

</tr>

<tr>

<td>

<input type="submit" name="submit" value="Upload Image" id="menu_button"/>    

</td>

<td>

<input type="reset" name="reset" value="Reset Details" id="menu_button"/>

<input type="hidden" name="actionID" value="Trial"/>

</td>

</tr>

</table>

</form>

No response so far.

I am not able to solve th error.

Please Assist....

Thanks avd for the tutorial.

I am going to try it but looking at the code i posted above, is there a problem with the code. The tutorial posted has the upload code but does not show uploading image to db.

@SagarSe7en you wouldn't believe when I tell that most of us are working so can only reply once off work, therefore can not per posters asap demand (sorry for sarcasm, couldn't resist)

To add on what _avd already provided I need to remind that data should be stored as BLOB object that is supported in many DBs now. See Oracle example

Peter i appreciate the help you provide me.

I even followed the steps as shown in the oracle example.

The image field is also a BLOB field in the Database. I am aware that they are to be storec as BLOB. The only HELP i am asking for is why the NullPointerException.

Every Single Step and code by code instructions were athered to.

Inspite of all that I still don't understand it does not pick the picture chosen from the JSP field. Noting an error that the image is a null parameter and there is no image selected by the user.

If you still believe that there is a problem with the code please assist me in showing where as the Netbeans IDE does not detect the error anywhere:

Upload.jsp

<form name="Upload_Image_Form" method="post" action="Relay" enctype="multipart/form-data">   

<table align="center" border="1" cellspacing="1px" style="width: auto; border-radius:3px; border-style: solid">

<tr>

<td>

<label style="font-family: Trebuchet MS; font-size: large ">Password</label>    

</td>

<td>

<input type="file" name="profile_image" value="" id="menu_button"/>    

</td>

</tr>

<tr>

<td>

<input type="submit" name="submit" value="Upload Image" id="menu_button"/>    

</td>

<td>

<input type="reset" name="reset" value="Reset Details" id="menu_button"/>

<input type="hidden" name="actionID" value="Upload_Profile_Image"/>

</td>

</tr>

</table>

</form>

Upload_Profile_Image.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package User;

import DataAccessObject.DAO;
import DataAccessObject.DAO_Interface;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author SaguWesker
 */
public class Upload_Profile_Image extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try 
    {

        RequestDispatcher rd = request.getRequestDispatcher("Relay");

        DAO_Interface Dao = DAO.getDAOInterface();        

        String File_Name = request.getParameter("profile_image");

        FileInputStream FIN = new FileInputStream(File_Name);

        if (!File_Name.equals(""))
        {
            Dao.Upload_Profile_Picture(request.getParameter("image"));
        }

        else
        {
            response.sendRedirect("index.jsp");
        }

    }

    catch (ClassNotFoundException CNFE)
    {
        System.out.println(CNFE);
    }

    catch (SQLException SQLE)
    {
        System.out.println(SQLE);
    }

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

    finally 
    {            
            out.close();

    }

    }

    // <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>
}

AndHere is the method from where the Insertion into the Database is performed:

Registration Method

public void Upload_Profile_Picture(String File_Name)

            throws ClassNotFoundException , SQLException , Exception
    {
        try
        {

            Connection SQLConnector = ConnectToTheDatabase();


            if (!File_Name.equals("")) 

            {

                PreparedStatement UploadStatement = SQLConnector.prepareStatement("INSERT INTO profile_image VALUES(?)");

                FileInputStream FIN = new FileInputStream(File_Name);

                UploadStatement.setBinaryStream(2, FIN, FIN.available());

                UploadStatement.execute();

                UploadStatement.close();

            } 

            else 
            {

                PreparedStatement UploadStatement = SQLConnector.prepareStatement("INSERT INTO IMAGES VALUES (?, empty_blob())");

                UploadStatement.execute();

                UploadStatement.close();


            }
                SQLConnector.close();

            }

        catch (ClassNotFoundException CNFE)
        {
            System.out.println(CNFE);
        }

        catch (SQLException SQLE)
        {
            System.out.println(SQLE);
        }
    }

Now tell me where the code is wrong. Exact steps followed yet the image upload fails simply because of anull pointer exception. It does not get the file tself. Does not get it as a parameter

Hello Experts, Anyone who has found out the reason behind the Problem why the program shows NullPointerException.

Thanks

If you can share the code on github or bitbucket I can have look at it, but unlikely to do it from current snippet

ok peter_budo i will share the code. Sending it to bitbucket along with the DAO.java , Upload_Profile_Image.java and the JSP Code as well.

You still did not provide bitbucket link where I can find this project

Hy Peter sorry for late reply.

We are experiencing Internet Problems countrywide which is why we were not able to access internet services during weekends.

Im really sorry bt im struggling with bitbucket and github.

Can i please put it on dropbox and then send u link?

Yes as long it is something that I can simply open in IDE instead of handcoding it.

Ok dropboxing it right away thanks aton genius :-)

Hy Peter Here is the link to the Project. Please show me where the prob is.

THANKS GENIUS :-)

Click Here

Hy Peter Did u manage to get the system?

Nope, I'm on holidays so I have restricted time for browsing internet. Downloading package now and I will let you know how it went...

Thanks Peter. For all your help and professional advice. Thank You Indeed Once Again :-)

Your web project organization is broken. Your libraries (JAR) in wrong place for start, they should be in PROJECT/WEB-INF/lib unlike at the moment in PROJECT directory on top level

(JAR) in wrong place fo

Ok i am making the changes and then re uploading to dropbox Thanks peter :-)

Hy Peter! I have re uploaded the file on dropbox. Please see how you can help me.

Thanking You In Advance SIR :-)

Hy Peter Link for the newly uploaded version:

Click Here

Hy Peter Did you try out the project i re-uploaded yesterday.

Hey Peter any luck?

I still don't know why i am getting null pointer expection like this:

01:01:50,744 INFO  [STDOUT] java.lang.NullPointerException

Nope was on bus tour whole day. Today I'm returning back to London so first possibility will be Monday evening.

ay I'm returning back to London so first possibility will be Monday evening.

Okay Do guide me why i am getting the Problem mentioned in my previous post. Thanks :-)

  1. What version of JBoss you using? (This will be tricky to set as I never used JBoss, but will try)
  2. I asked you to moved JARs to PROJECT/WEB-INF/lib where you just dropped them in PROJECT/WEB-INF
  3. Libraries are not linked properly you can see in NetBeans that under Libraries folder only commons are available, secondly if you look into folder structure through Windows Explorer OnlineShop/build/web/WEB-INF there is duplication of JARs as one set is on this level and next in lib folder. Try Clean Build and see if that removes duplication otherwise you need to check your settings

Also if you can include database structure in some backup sql file that would help (I wouldn't need to create it by hand)

Okay Peter. I created a Libraries Folder by creating a new project in netbeans. Currently Copy Pasting all the code from previous project. Will dropbox with SQL File. Database name is iCorp in case if u try to export and it shows no database selected just create a database named iCorp and then u cn export the tables to the database selected.

Providing new link as soon as possible.

Thanks FRIEND :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.