1

我从 .jsp 文件中的组合框获取值到 servlet 时遇到问题。我在其他 servlet 中使用 request.getParameter 方法,它可以工作。在这堂课中它没有。我也试图从文本字段中获取价值到这个 servlet,但也不起作用。我不知道如何解决这个问题。

我有这样的组合框:

<form action="upload" method="POST" enctype="multipart/form-data"> 
            <p class="folders_save">Folder:
                <select name="folders1" id="user">
                        <% 
                        user = (User)session.getAttribute("user");
                        listOfFolders = user.listOfFolders(); 
                        if(listOfFolders != null){
                           for(File file : listOfFolders){
                                out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
                            }
                           }
                        %> 
                    </select>

                     </p>
                <input class="pole" type="file" name="file" />
                <input class="wrzuc" type="submit" value="Wrzuc!">
            </form>  

我正在努力获得价值:

String folder = request.getParameter("folders1");

我的jsp文件

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<%@ page import="tools.User" %>
<%@ page import="java.io.File" %>
<%@ page import="java.text.DecimalFormat" %>
<%@page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Serwer dysku sieciowego </title>
</head>
<body>
<div class="container">
<div class="ramka_zaproszenie">

    <% 
        File[] listOfFolders;
        User user;
        String username;
        String status = null;
        if(session.getAttribute("user")!=null){
            user = (User)session.getAttribute("user");
            username = user.getLogin();
            status = user.getType().toString();
        } else {
            username = "unknown";
        }
    %>
    <p class="loguj">Witaj, <%= username %>!</p><br>
    <% if(session.getAttribute("user")!=null){ %>
        <p class="tekst">Wrzuc plik na serwer:</p>

        <form action="upload" method="POST" enctype="multipart/form-data"> 
        <p class="folders_save">Folder:
            <select name="folders1" id="user">
                    <% 
                    user = (User)session.getAttribute("user");
                    listOfFolders = user.listOfFolders(); 
                    if(listOfFolders != null){
                       for(File file : listOfFolders){
                            out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
                        }
                       }
                    %> 
                </select>

                 </p>
            <input class="pole" type="file" name="file" />
            <input class="wrzuc" type="submit" value="Wrzuc!">
        </form>

    <form action="folder" method="get">
        <p class="tekst"> Folder: <br><input class="pole" id="Folder" type="text" name="folderName" /> 
        <br /></p>
        <input class="zatwierdz" type="submit" id="submit" value="Utwórz" /><br>
    </form>
    <br />
    <% if(status.equalsIgnoreCase("ADMIN")){ %>
        <a class="wroc" href="zmiana_rozmiaru.jsp">Zmiana Pojemnosci</a>
    <%}%>
        <br />
        <br /> 
        <p class="tekst">Posiadane pliki na serwerze:</p>

        <form method="post">
        Folder:
            <select name="folders">
            <option value=0 selected="selected" >Wybierz folder</option>
                    <% 
                    user = (User)session.getAttribute("user");
                    listOfFolders = user.listOfFolders(); 
                    if(listOfFolders != null){
                       for(File file : listOfFolders){
                            out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
                        }
                       }
                    %> 
                </select> 
                <input type="submit" value="Wybierz"><br>
                </form>
        <br />  
        Pliki z folderu: <%=request.getParameter("folders")%>

        <center><table id="tabela">
        <tr class="alt">
        <th>Nazwa</th>
        <th>Rozmiar</th>
        <th>Pobierz</th>
        <th>Usun</th>
        </tr>
        <% 
        System.out.println(request.getParameter("folders"));
           user = (User)session.getAttribute("user");
           File[] listOfFiles = user.listOfFiles(request.getParameter("folders"));
           if(listOfFiles != null){
           for(File file : listOfFiles){
                DecimalFormat twoDForm = new DecimalFormat("#.##");
                out.print("<tr class=\"alt\"><td>" + file.getName()+"</td><td>" +twoDForm.format((double)file.length()/1024.0)+" KB</td><td align=center> <a href=\"download?filePath="+file.getAbsolutePath()+"\"><img border=\"0\" src=\"downloadsmall.png\"></a></td><td align=center><a src=\"deletesmall.png\" href=\"delete?filePath="+file.getAbsolutePath()+"\" ><img border=\"0\" src=\"deletesmall.png\"></a></td></tr>");
            }
           }
        %>

        </table>
        </center><br>
        <form action="logout" method="post">
            <input type="image" src="wylacznik.png" id="submit">
        </form>
        <br><br>
            <%
        if (session.getAttribute("warning") != null) {
    %>
    <span><%= session.getAttribute("warning") %></span> 
    <%
        session.removeAttribute("warning");
        }
    %>

    <% } %>
    <div class="footer">Copyright 2013 by JavaProjectTeam.</div>
    </div>
    </div>
</body>
</html>

还有我的 servlet 文件

<pre>package servlets;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;

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

import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

import tools.Connector;
import tools.User;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private File file ;

   public void init(){
      // Get the file location where it would be stored.
      filePath = getServletContext().getInitParameter("file-upload");
   }
   public void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      request.setCharacterEncoding("UTF-8"); 
      String folder = request.getParameter("folders1");
      HttpSession session = request.getSession(true);
      User user = (User)session.getAttribute("user");
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");

      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
          session.setAttribute("warning", "Nie masz zadnych plikow");
          response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
          response.setHeader("Location", "hello.jsp");
          return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax(user.getSpace() * 1024);

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fileName = fi.getName();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+ 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write(file);
            System.out.println(file.getName());
            try{
                Connection connection = new Connector().getConnection();
                DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
                otherSymbols.setDecimalSeparator('.');
                otherSymbols.setGroupingSeparator('.'); 
                DecimalFormat twoDForm = new DecimalFormat("#.##", otherSymbols);
                System.out.println(twoDForm.format((double)file.length()/1024.0));
                connection.createStatement().executeUpdate("UPDATE `users` SET `space` = `space`-"+twoDForm.format((double)file.length()/1024.0)+" where id="+user.getId());
            } catch(SQLException e){
                e.printStackTrace();
            }
            session.setAttribute("warning", "Plik został dodany do wirtualnego dysku.");
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", "hello.jsp");

         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
        session.setAttribute("warning", "File is too big! Only "+user.getSpace()+"KB left.");
        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", "hello.jsp");

   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");


   } 
}<code>
4

1 回答 1

3

这是因为您正在发送一个multipart/form-data请求,而servlet默认不支持该请求。然而,我注意到您仍在使用“旧版”Apache Commons FileUpload 来获取上传的文件,而不是提供的新 Servlet 3.0 HttpServletRequest#getPart()。在这种情况下,您基本上有两个选择:

  1. 坚持 Commons FileUpload。您应该在您当前完全忽略的else块中收集常规表单字段。if (!fi.isFormField())

    if (!fi.isFormField()) {
        // Collect uploaded file from fi.
    } else {
        // Collect normal form field from fi.
    }
    
  2. 摆脱 Commons FileUpload 并使用@MultipartConfig注释。

    @WebServlet("/upload")
    @MultipartConfig
    public class UploadServlet extends HttpServlet {
    

    通过这种方式,您可以获取文件request.getPart()并继续使用request.getParameter()常规表单字段的常用方式。

也可以看看:


与具体问题无关,这不是组合框,而是下拉菜单。组合框是可编辑的下拉菜单。此外,在 JSP 中编写 Java 代码是一种不好的做法。Java 代码像 servlet 一样属于 Java 类。要循环选项,请使用 JSTL <c:forEach>。而且,在像 servlet 这样的 Java 类中编写 HTML 代码是一种不好的做法。HTML 代码属于 JSP 文件。用于RequestDispatcher#forward()在 JSP 中显示结果。另请参阅我们的 servlets wiki 页面

哦,您的 servlet 中有一个主要的线程安全问题。在应用程序生命周期中只有一个 servlet 实例在所有 HTTP 请求中共享。那些领域

private boolean isMultipart;
private String filePath;
private File file ;

当多个用户同时使用同一个 servlet 时,将在所有 HTTP 请求之间共享,从而导致潜在的重大问题。摆脱它们并将它们移动到doXxx()方法块内。

于 2013-02-14T13:41:32.807 回答