无法使用jsp使用文件保存表单数据

时间:2016-04-07 09:08:20

标签: mysql forms jsp

我正在尝试使用jsp-servlet设计一个页面,这将帮助用户upload documents获取案例/客户端。这是它应该如何工作 -

  
      
  1. 从选项框

  2. 中可用的列表中选择客户端   
  3. 根据选择 - 客户的基本信息将是   显示

  4.   
  5. 将激活上传文件的控件

  6.   
  7. 然后,用户可以逐个上传文档

  8.   
  9. Save Details会将clientIDDocumentNames保存在MySQL中   表

  10.   

我已经分别找到了步骤#1到#5,他们工作正常。当我将它们放在一页上时,问题就开始了。然后我意识到因为我的表单有enctype="multipart/form-data",所以在我的控制器中无法访问表单(clientID, name, etc)上填充的其他值,以便在MYSQL表中保存ClientDocument information

如果有人可以指导我/指出我要遵循的榜样,那将会很有帮助。非常感谢你的帮助。

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cts.controller;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cts.dao.CaseDocumentDAO;
import com.cts.model.CaseDocument;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CaseDocumentController extends HttpServlet {

private static final long serialVersionUID = 1L;
 private static String INSERT_OR_EDIT = "/ctsCaseDocuments.jsp";
 //private static String LIST_CASEDETAIL = "/ctsListCaseDetail.jsp";
 private CaseDocumentDAO dao; 

 private final String UPLOAD_DIRECTORY = "d:/uploads";


  public CaseDocumentController() {
    super();
    dao = new CaseDocumentDAO();

}
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward = "";
    String action = request.getParameter("action");       
    forward = INSERT_OR_EDIT;
    request.setAttribute("casemasters", dao.getAllCaseMaster());

    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    CaseDocument casedocument = new CaseDocument();

   if (request.getParameter("GetDetails") != null) {

        String str = request.getParameter("cad_FileName1");
        System.out.println(str);
        String selected_Comments[] = request.getParameterValues("cad_FileName1");
        for (String comment : selected_Comments) {
            System.out.println(comment);
            request.setAttribute("casedetail", dao.getCaseDetailById(Integer.parseInt(comment)));

            request.setAttribute("casemasters", dao.getAllCaseMaster());
            request.getRequestDispatcher("/ctsCaseDocuments.jsp").forward(request, response);

        }

    } 

   if (ServletFileUpload.isMultipartContent(request)) {
        try {
            String fname = null;
            String fsize = null;
            String ftype = null;
            List<FileItem> multiparts = new ServletFileUpload(
                    new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    fname = new File(item.getName()).getName();
                    fsize = new Long(item.getSize()).toString();
                    ftype = item.getContentType();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator
                            + fname));
                }
            }
            // File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
            request.setAttribute("name", fname);
            request.setAttribute("size", fsize);
            request.setAttribute("type", ftype);
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to "
                    + ex);
        }

    } else {
        request.setAttribute("message",
                "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/ctsCaseDocuments.jsp").forward(request, response);
 }



}

JSP代码 -

<%-- 
Document   : ctsCasePayments
Created on : 27 May, 2016, 10:35:35 AM
Author     : Admin
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Upload Case Documents</title>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="css/sb-admin.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" href="css/prism.css">
    <link rel="stylesheet" href="css/chosen.css">
    <style type="text/css" media="all">
        /* fix rtl for demo */
        .chosen-rtl .chosen-drop { left: -9000px; }
    </style>

    <script src="/js/jquery.validate.js"></script> 
    <script>
        $.validator.setDefaults({
        submitHandler: function () {
            alert("submitted!");
        }
        });
        });</script>


    <style>
        div.dataTables_wrapper {
            width: 1100px;
            margin: 0 auto;
        }
    </style>

    <style>

        #leftContainer {
            float:left;
        }

        #rightContainer {
            float:none;
        }
    </style>


</head>

<body>

    <div id="wrapper">

        <!-- Navigation -->
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="index.html">SB Admin</a>
            </div>
            <!-- Top Menu Items -->
            <ul class="nav navbar-right top-nav">

                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <%=session.getAttribute("name")%> <b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li>
                            <a href="#"><i class="fa fa-fw fa-user"></i> Profile</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-fw fa-envelope"></i> Inbox</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-fw fa-gear"></i> Settings</a>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <a href="LogOutController"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
                        </li>
                    </ul>
                </li>
            </ul>
            <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
            <div class="collapse navbar-collapse navbar-ex1-collapse">
                <ul class="nav navbar-nav side-nav">
                    <li class="active">
                        <a href="DashBoardController?action=listDairy"><i class="fa fa-fw fa-dashboard"></i> Dashboard</a>
                    </li>                  

                    <li>
                        <a href="javascript:;" data-toggle="collapse" data-target="#demo"><i class="fa fa-fw fa-arrows-v"></i> Home <i class="fa fa-fw fa-caret-down"></i></a>
                        <ul id="demo" class="collapse">
                            <li>
                                <a href="DashBoardController?action=listDairy">Dashboard</a>
                            </li>
                            <li>
                                <a href="ARCILBoardController?action=listDashboard">ARCIL Dashboard</a>
                            </li>



                        </ul>
                    </li>  
                    <li>
                        <a href="javascript:;" data-toggle="collapse" data-target="#demo1"><i class="fa fa-fw fa-arrows-v"></i> Operations <i class="fa fa-fw fa-caret-down"></i></a>
                        <ul id="demo1" class="collapse">
                            <li>
                                <a href="AdvocateController?action=listAdvocate">Advocates</a>
                            </li>
                            <li>
                                <a href="UserController?action=listUser">Users</a>
                            </li>
                            <li>
                                <a href="ClientController?action=listClient">Clients</a>

                            </li>
                            <li>
                                <a href="CourtController?action=listCourt">Courts</a>
                            </li>
                            <li>
                                <a href="DashBoardController?action=listDairy">Registrar</a>
                            </li>
                            <li>
                                <a href="#">Case Category</a>
                            </li>
                            <li>
                                <a href="CaseStageController?action=listCaseStage">Case Stage</a>
                            </li>
                            <li>
                                <a href="DocumentController?action=listDocument">Documents</a>
                            </li>
                        </ul>
                    </li> 
                    <li>
                        <a href="javascript:;" data-toggle="collapse" data-target="#demo2"><i class="fa fa-fw fa-arrows-v"></i> Case <i class="fa fa-fw fa-caret-down"></i></a>
                        <ul id="demo2" class="collapse">

                            <li>
                                <a href="CaseDetailController?action=listCaseDetail">Case Diary</a>
                            </li>
                            <li>
                                <a href="CaseDocumentController?action=listDocument">Case Documents</a>
                            </li>
                            <li>
                                <a href="#">Notice Information</a>
                            </li>
                            <li>
                                <a href="#">Allocate Cases</a>
                            </li>
                            <li>
                                <a href="#">Payments</a>
                            </li>                               
                        </ul>
                    </li>

                </ul>

            </div>
            <!-- /.navbar-collapse -->
        </nav>


        <div id="page-wrapper">

            <div class="container-fluid">

                <!-- Page Heading -->
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header">
                            Maintain Case Expenses
                        </h1>
                        <ol class="breadcrumb">
                            <li>
                                <i class="fa fa-dashboard"></i>  <a href="index.jsp">Dashboard</a>
                            </li>
                            <li class="active">
                                <i class="fa fa-edit"></i>  Maintain Case Expenses
                            </li>
                        </ol>
                    </div>
                </div>
                <!-- /.row -->

                <div class="row">
                    <div class="col-lg-6">
                        <%-- <form role="form" method="POST" class="register" action='CaseExpensesController' name="frmAddCaseDetail" onsubmit="return ValidateEndDate(this)">--%>
                        <form role="form" method="POST" class="register" action='CaseDocumentController' name="frmUploadDocuments" >
                            <div class="form-group">
                                <p>
                                <table>
                                    <tr>
                                        <td>
                                            <select data-placeholder="Select Case..." name ="cad_FileName1" class="chosen-select" style="width:450px;" >
                                                <c:forEach items="${casemasters}" var="casemaster">                                                
                                                    <option value="${casemaster.cad_ID}" ${casedetail.cad_ID == casemaster.cad_ID ? 'selected' : ''}>${casemaster.cad_CaseNo} || ${casemaster.cad_FileName}</option>
                                                </c:forEach>
                                            </select>
                                        </td>
                                        <td> <lable>&nbsp;&nbsp;</lable> </td>                                            
                                    <td><button type="submit" name="GetDetails" value="GetDetails" class="btn btn-primary">Get Details</button> </td>
                                    <td> <lable>&nbsp;&nbsp;</lable> </td>
                                    <td><button type="submit" name="AddCase" value="AddCase" class="btn btn-primary">New Case</button> </td>
                                    </tr>
                                </table>
                                </p>

                                <div class="form-group">




                                    <p>     
                                    <table>
                                        <tr>

                                            <td><input type="text" readonly="readonly" style="width:200px;"  class="form-control" placeholder="Case ID" name="cad_id" value="<c:out value="${casedetail.cad_ID}" />" /> </td>
                                            <td> <lable>&nbsp;&nbsp;&nbsp;&nbsp;</lable> </td>
                                        <td><input type="text" readonly="readonly" style="width:220px;" class="form-control" placeholder="Registration No" name="cad_RegNo" value="<c:out value="${casedetail.cad_RegNo}" />" /> </td>
                                        <td> <lable>&nbsp;&nbsp;&nbsp;&nbsp;</lable> </td>
                                        <td><input type="text" readonly="readonly" style="width:250px;" class="form-control" placeholder="Case Number" name="cad_CaseNo" value="<c:out value="${casedetail.cad_CaseNo}" />" /> </td>
                                        <td> <lable>&nbsp;&nbsp;&nbsp;&nbsp;</lable> </td>
                                        <td><input type="text" readonly="readonly" style="width:250px;"  class="form-control" placeholder="File Number" name="cad_FileNo" value="<c:out value="${casedetail.cad_FileNo}" />" /> </td>

                                        </tr>
                                    </table>
                                    </p>

                                    <p>     
                                    <table>
                                        <tr>
                                            <td><input type="text" readonly="readonly" style="width:475px;" class="form-control" placeholder="File Name" name="cad_FileName" value="<c:out value="${casedetail.cad_FileName}" />" /> </td>
                                            <td> <lable>&nbsp;&nbsp;&nbsp;&nbsp;</lable> </td>
                                        <td><input type="text" readonly="readonly" style="width:475px;" class="form-control" placeholder="Client Name" name="cad_ClientName" value="<c:out value="${casedetail.cad_ClientName}" />" /> </td>
                                        </tr>
                                    </table>
                                    </p>


                                    <input type="hidden" readonly="readonly" style="width:200px;"  class="form-control" placeholder="CaseExpenseID" name="cce_ID" value="<c:out value="${caseexpense.cce_ID}" />" />
                                    <input type="hidden" readonly="readonly" style="width:200px;"  class="form-control" placeholder="Case ID" name="pcad_ID" value="<c:out value="${caseexpense.cad_ID}" />" />
                                    <input type="hidden"  class="form-control" name="cce_DeleteFlag" value="<c:out value="0"/>" /> 
                                    <input type="hidden"  class="form-control" name="cce_ActiveFlag" value="<c:out value="true" />" /> 
                                    <input type="hidden"  class="form-control" name="cce_CreateDate" value="<fmt:formatDate pattern="dd/MM/yyyy" value="<%= new java.util.Date()%>" />" />                
                                    <input type="hidden"  class="form-control" name="cce_CreateUser" value="<c:out value="1" />" />                 
                                    <input type="hidden"  class="form-control" name="cce_ModifyDate" value="<fmt:formatDate pattern="dd/MM/yyyy" value="<%= new java.util.Date()%>" />" />                
                                    <input type="hidden"  class="form-control" name="cce_ModifyUser" value="<c:out value="1" />" /> 

                                    <p>
                                        <%--<button type="submit" name="SaveDetails" value="SaveDetails" class="btn btn-primary" onClick="return ValidateEndDate();">Submit</button> --%>
                                        <button type="submit" name="SaveDetails" value="SaveDetails" class="btn btn-primary" >Submit</button>
                                        <button type="reset" class="btn btn-default">Reset Button</button>
                                    </p>
                                </div>


                            </div>        
                            <script type="text/javascript">
                                        function ValidateEndDate() {

                                            var StartDate = document.getElementById('ccd_PreviousDate').value;

                                            var EndDate = document.getElementById('ccd_CurrentDate').value;
                                            var tmpStartDate = StartDate.split("/");
                                            var tmpEndDate = EndDate.split("/");

                                            var eDate = new Date(tmpEndDate[1] + '/' + tmpEndDate[0] + '/' + tmpEndDate[2]);
                                            var sDate = new Date(tmpStartDate[1] + '/' + tmpStartDate[0] + '/' + tmpStartDate[2]);
                                            if (StartDate != '' && StartDate != '' && sDate.getTime() > eDate.getTime()) {

                                                document.getElementById('NextDateError').innerText = "Please ensure that the Next Date is greater than Previous Date"
                                                return false;
                                            }
                                            else
                                                return true;
                                        }
                            </script>

                            <script type="text/javascript">
                                Toggle();
                                function Toggle() {
                                    if (document.frmAddCaseDetail.cboxToggle.checked) {
                                        return ValidateEndDate();
                                    }

                                }
                            </script>
                            <script>
                                function ctsOpenCaseStaePopUp() {
                                    window.open("ctsCaseStage.jsp", null, "height=438, width=600, status=yes, toolbar=no, menubar=no, location=no");
                                }
                            </script>
                            <script>
                                function ctsOpenCourtPopUp() {
                                    window.open("ctsCourtRegistration.jsp", null, "height=480, width=600, status=yes, toolbar=no, menubar=no, location=no");
                                }
                            </script>
                        </form>

                        <form method="post" action="CaseDocumentController" enctype="multipart/form-data">
                            Choose a file : <input type="file" name="file"> <input
                                type="submit" value="upload">

                            <div id="result">
                                <h3>${requestScope["message"]}</h3>
                                <br>
                            </div>
                            File name : ${requestScope["name"]}
                            <br> File size : ${requestScope["size"]}
                            <br> File type : ${requestScope["type"]}
                        </form>

                    </div>




                </div>
                <!-- /.row -->

            </div>
            <!-- /.container-fluid -->

        </div>
        <!-- /#page-wrapper -->

        <!-- /#wrapper -->

        <!-- jQuery -->
        <script src="js/jquery.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>
        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
        <script src="js/chosen.jquery.js" type="text/javascript"></script>
        <script src="js/prism.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
                                var config = {
                                    '.chosen-select': {},
                                    '.chosen-select-deselect': {allow_single_deselect: true},
                                    '.chosen-select-no-single': {disable_search_threshold: 10},
                                    '.chosen-select-no-results': {no_results_text: 'Oops, nothing found!'},
                                    '.chosen-select-width': {width: "95%"}
                                }
                                for (var selector in config) {
                                    $(selector).chosen(config[selector]);
                                }
        </script>
</body>

0 个答案:

没有答案