简体   繁体   English

将文件从JSP发送到调用接口方法的控制器-如何从该请求上传文件?

[英]Send a file from JSP to controller which calls a method of interface -How do I upload a file from that request?

hello every one i'm working on a project. 你好,我正在做一个项目。

Hope u can help me in solving my problem.. I'm struggling for 5 DAYS!! 希望你能帮助我解决我的问题。.我正在努力5天!

in a module which is assigned to me I have to upload a file, title, category, uploadedby details from a JSP to controller.do which stores the request and responce in a method named execute() which is present in Command.java Interface . 在分配给我的模块中,我必须将文件,标题,类别,按详细信息从JSP上传到controller.do,后者将requestresponce存储在Command.java 接口中名为execute()的方法中。

now when i pass all the Upload form details,, it goes all the way across to a class named ResourceCommand.java implements Command which calls a DAO and stops execution in middle !!!! 现在,当我传递所有Upload表单详细信息时,它会一直处理到名为ResourceCommand.java implements Command的类ResourceCommand.java implements Command ,该ResourceCommand.java implements Command调用DAO并在中间停止执行!

part of code from Upload.jsp Upload.jsp的部分代码

<form name="myform_up" method="post" action = "Controller">  
         <input type="hidden" name="form_action" value="resource" /> 
         <input type="hidden" name="action" value="insert" />
   <table>      
         <tr>
            <td>Document Title <font color="red">*</font></td></tr>
        <tr>
            <td><input type="text" name="name" /></td></tr>
        <tr>
            <td>Category <font color="red">*</font>
            <select name="cat">
                <option value="Java" selected >Java Material</option>
                <option value="Net">.Net Material</option>
                <option value="C">C and C# Material</option>
            </select></td>
        </tr>
            <input type="hidden" name="uploadedby" value="<jsp:getProperty name="userBean" property="user" />" />
        <tr>
            <td>Upload A file:
            <input type="file" name="file1"/></td>
        </tr>
        <tr>
            <td><br/><input type="checkbox" name="t_condition" checked />I Had received Copyrights for this Document</td>
        </tr>
        <TR>
            <td ALIGN="CENTER"><br/>
            <INPUT class="button blue" TYPE="submit" value="Upload" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <INPUT class="button red" TYPE="reset" value="Clear" />
            </td></TR>
    </TABLE>
</FORM>

part of code from Controller.java Controller.java的部分代码

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("resource", new ResourceCommand());

    }

    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 {

        String formAction = request.getParameter("form_action");
System.out.println("implementing formAction = " + formAction);
        Commands command = (Commands) commands.get(formAction);     
                             command.execute(request, response);            
    }
}

part of code from ResourceCommand.java ResourceCommand.java中的部分代码

public class ResourceCommand extends HttpServlet  implements Commands{
    private static final long serialVersionUID = 1L;
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if ("insert".equalsIgnoreCase(request.getParameter("action"))) {
            this.addResource(request, response);
        }
    }

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

        ResourceBean ResourceBean = new ResourceBean();
        mapToResourceBeans(request, ResourceBean);

        String result = null;
        try {
            result = new ResourceDAO().uploadResource(request, ResourceBean);
        } catch (Exception ex) {
            System.err.println(" Error in inserting new resource");
        }
        if ("success".equalsIgnoreCase(result)) {
                       // if Block CODE
        }

        else {
                       //Else block CODE
        }       
    }
    private void mapToResourceBeans(HttpServletRequest request,
            ResourceBean ResourceBean) {        
        ResourceBean.setName(request.getParameter("name"));
        ResourceBean.setCat(request.getParameter("cat"));
        ResourceBean.setUploadedby(request.getParameter("uploadedby"));             
    }   
}

part of code from Command.java Command.java的部分代码

public interface Commands {

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

}

part of code from ResourceDAO.java ResourceDAO.java中的部分代码

public class ResourceDAO {
        static final String SUCCESS = "success";
        static final String FAILURE = "failure";

        static Logger log = Logger.getLogger("com.a");

        public String uploadResource(HttpServletRequest request,
                ResourceBean newResource) throws FileNotFoundException {

            String result = null;
            PreparedStatement stmtInsert = null;    
            // Create a Database Connection
            Connection con = ConnectionDAO.getJDBCConnection();
            try {
            PreparedStatement pstmt = con
                        .prepareStatement("INSERT INTO resource(name, cat, uploadedby, file) values(?,?,?,?)");
                pstmt.setString(1, newResource.getName());
    System.out.println(newResource.getName());

                pstmt.setString(2, newResource.getCat());
    System.out.println(newResource.getCat());

                pstmt.setString(3, newResource.getUploadedby());
    System.out.println(newResource.getUploadedby());

                String file = request.getParameter("file1");
    System.out.println("0");

                File f = new File(file);
    System.out.println("1");

                FileInputStream fis = new FileInputStream(f);
    System.out.println("2");

                pstmt.setBinaryStream(4, fis, (int) f.length());
    System.out.println("3");    
                int rows = pstmt.executeUpdate();

                result = SUCCESS;

                if (rows != 1) { result = FAILURE; }

            } catch (SQLException ex) {
                result = FAILURE;
                ConnectionDAO.rollbackJDBCConnection(con);
                ex.printStackTrace();
            } finally {
                ConnectionDAO.commitJDBCConnection(con);
                ConnectionDAO.closeStatement(stmtInsert);
                ConnectionDAO.closeJDBCConnection(con);
            }
            return result;
        }    
    }

Console Display.. 控制台显示

implementing formAction = resource
 Error in inserting new resource
123
Net
null
0
1
i am going back to addResource page

If i place enctype="multipart/form-data" in form TAG.. then i will get this.. 如果我将enctype="multipart/form-data"放在TAG表格中,那么我会得到这个。

java.lang.NullPointerException
    com.kbcss.controller.Controller.processCommand(Controller.java:57)
    com.kbcss.controller.Controller.doPost(Controller.java:49)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 

I am completely LOST..Plz HELP... 我完全迷失了。.Plz帮助...

Is this line 56? 这是第56行吗? The one before the error? 前一个错误?

Commands command = (Commands) commands.get(formAction);    

It may be returning null if the command isn't found in the commands map (which you didn't show). 如果在commands映射中未找到该commands (未显示),则可能返回null You should at least check for a valid command being returned from the map. 您至少应检查是否从地图返回了有效命令。

A Map will return null when something isn't found to match. 如果找不到匹配的内容,则Map将返回null On the next line you use it and would get a NullPointerException . 在下一行中,您将使用它,并将获得NullPointerException

我发现我应该使用Serlvet 3.0来使事情正常工作。。我感谢大家为我的代码付出了自己的努力:p ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Spring,JSP中将表单值从jsp文件发送到控制器? - How can I send form values from jsp file to controller in Spring, JSP? 将Mulitpart文件从Controller发送到JSP(春季) - Send Mulitpart file from Controller to JSP (Spring) 如何在Spring中将数据从Controller发送到JSP页面? - How do I send data from a Controller to a JSP page in Spring? 如何将请求从同一JSP文件发送到多个Servlet? - How to send request from same JSP file to Multiple Servlets? 从jsp上传文件 - Upload file from jsp 如何从前端服务器发送文件到后端服务器(用于上传),该服务器接受来自客户端浏览器的发布请求(表单数据 - &gt;文件输入)? - How to Send a file to backend server (for upload) from frontend server which is accepting post request from client browser (form data -> file input)? 在jsp中上传文件后,为什么无法从请求中访问参数? - Why I can't get access to parameters from a request after upload a file in jsp? 如何从javabean的jsp文件中调用方法? - How do I call a methods in an jsp file from a javabean? 如何从 Groovy controller 发送 pdf 文件以由我的 Z9784E91C7B2657891722 端点处理? - How do I send a pdf file from Groovy controller to be processed by my Flask end point? 如何调用返回 JSP 文件中列表的 Java 方法? - How do I invoke a Java method which returns a list in JSP file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM