0

i am developing a project KNOWLEDGE based community sharing system. in which users can login and share their resources to other Users....

I'm getting a problem in uploading a file to mysql database....

PS..my Instructor strictly Says to use MVC architecture So, i have to use the same.. So i have created only one Servlet named Controller.java. here i will redirect to other java programs for calculations...

Here is the code for Controller.java

package com.kbcss.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;

public class Controller extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Controller() {super();}

    @SuppressWarnings("rawtypes")
    private Map commands = new HashMap();

    @SuppressWarnings("unchecked")
    public void init(ServletConfig config) throws ServletException{
        super.init();

        System.out.println("i am in init");

        this.commands.put("login", new LoginCommand());
        this.commands.put("user", new UserCommand());
        this.commands.put("resource", new ResourceCommand());

        System.out.println("i am about to exit init");        
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("i am in doget");
        processCommand(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("i am in dopost");
        processCommand(request, response);
    }

    private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("i am in processCommand");

        String formAction = request.getParameter("form_action");

        System.out.println("i am in processCommand state 2");

        Commands command = (Commands) commands.get(formAction);     
                             command.execute(request, response);

        System.out.println("i am about to exit processCommand");
    }
}

and here is the code for saving the resources to MY database table.... Named ResourceCommand .java

package com.kbcss.command;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;

import com.oreilly.servlet.MultipartRequest;

public class ResourceCommand extends HttpServlet  implements Commands{

    private static final long serialVersionUID = 1L;

    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {

            //
            // JNDI to connect to database
            //
            Connection conn = null;
            Context initContext = new InitialContext();
            Context envContext = (Context)initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
            conn = ds.getConnection();

            //
            // Save file(s) temporarily to filesystem
            //
            MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
            Enumeration files = multi.getFileNames();
            String filename = "";
            File f = null;

            while(files.hasMoreElements()) {
              String name = (String)files.nextElement();
              filename = multi.getFilesystemName(name);
              String type = multi.getContentType(name);
              f = multi.getFile(name);
            }

            //
            // Insert file into database
            //
            InputStream is = new FileInputStream(f);
            String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
            PreparedStatement stmt = conn.prepareStatement(sql);
            // Set some Title
            stmt.setString(1, "some thing");
            // Set some category
            stmt.setString(2, ".net");
            // Set some user
            stmt.setString(3, "sri");
            // Set Filename
            stmt.setString(4, f.getName());
            // Set the data
            stmt.setBinaryStream(5, is, (int) f.length());
            // Set Likes
            stmt.setInt(6, 2);

            stmt.executeUpdate();
            is.close();

            //
            // Release connection
            //
            if (stmt != null) {
              try { stmt.close(); } catch (SQLException e) { ; }
              stmt = null;
            }
            if (conn != null) {
              try { conn.close(); } catch (SQLException e) { ; }
              conn = null;
            }
          } catch(Exception e) {
            System.out.println(e);
          }     
    }
}

And here is the jSP file where i will upload from....

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>UPLOAD FILE page</title></head>
<body>

<form method="post" action="Controller" enctype="multipart/form-data">
    <input type="hidden" name="form_action" value="resource" /> 
        <b>File to upload to database:</b>     
    <input type="file" name="attachment" size="36">
    <input type="submit" value="Upload">
</form>

</body></html>

And this is the error i'm getting :(

INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
    at com.kbcss.controller.Controller.processCommand(Controller.java:69)
    at com.kbcss.controller.Controller.doPost(Controller.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

and by the way..i have created a Command.java interface here it is.

package com.kbcss.command;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public interface Commands {

    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

}

Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ i'm stuck for a day and Half and have no clue what i'm doing...

This is what happens if u ask an electrical engineering student to do a Java Project !!!!

GREAT GREAT thanks from My side.....

Srivastav
  • 361
  • 3
  • 15

1 Answers1

2

Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.

Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).

One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:

private Map<String,Command> commands = new HashMap<String,Command>();

After you do that, you shouldn't have to suppress the warning on the Map.

musical_coder
  • 3,886
  • 3
  • 15
  • 18
  • i tried a different approach..See here>> http://stackoverflow.com/questions/19386352/send-a-file-from-jsp-to-controller-which-calls-a-method-of-interface-how-do-i-u I am afraid that new approach is also not Working.. – Srivastav Oct 17 '13 at 05:56