0

我正在开发一个基于项目知识的社区共享系统。用户可以在其中登录并将其资源共享给其他用户....

我在将文件上传到 mysql 数据库时遇到问题....

PS..我的讲师严格说要使用 MVC 架构所以,我必须使用相同的..所以我只创建了一个名为 Controller.java 的 Servlet。在这里,我将重定向到其他 java 程序进行计算...

这是 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");
    }
}

这是将资源保存到我的数据库表的代码......命名为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);
          }     
    }
}

这是我将从中上传的jSP 文件....

<%@ 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>

这是我得到的错误:(

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)

顺便说一句..我在这里创建了一个Command.java 接口。

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;

}

谁能指导我PLZZZZZZZZZZZZZZZZZZZ我被困了一天半,不知道我在做什么......

如果您要求电气工程专业的学生进行 Java 项目,就会发生这种情况!!!!

非常感谢我这边.....

4

1 回答 1

2

机会commands.get(formAction);是回来了null,所以command也是null。当您调用 时command.execute(request, response);,您正在尝试访问null对象中的某些内容。这会给你一个NullPointerException.

使用您的打印语句来确定formAction获得异常时的确切值。然后验证您是否将该字符串的密钥放入commands(如果不是"login""user""resource",因为您已经输入了这些)。

可能导致问题的另一件事是您需要将类类型添加到您的Map. 将其更改为:

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

在你这样做之后,你不应该在Map.

于 2013-10-10T06:30:23.257 回答