在jsp中从组合框获取值到servlet

时间:2013-02-14 10:35:50

标签: java jsp servlets combobox

我有问题从我的.jsp文件中的combobox获取值到servlet。 我使用方法request.getParameter i其他servlet,它的工作原理。在这堂课中没有。 我也试图从文本字段获取值到这个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>

1 个答案:

答案 0 :(得分:3)

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

  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()常规表单字段的常用方式。

  3. 另见:


    无声的具体问题,这不是一个组合框,但这是一个下拉列表。组合框是可编辑的下拉列表。此外,在JSP中编写Java代码是一种不好的做法。 Java代码属于Java类,如servlet。要循环选项,请使用JSTL <c:forEach>。而且,在像Java servlet这样的Java类中编写HTML代码是一种不好的做法。 HTML代码属于JSP文件。使用RequestDispatcher#forward()在JSP中显示结果。另见our servlets wiki page

    哦,你的servlet中存在一个主要的线程安全问题。应用程序生命周期中只有一个servlet实例,它在所有HTTP请求之间共享。那些字段

    private boolean isMultipart;
    private String filePath;
    private File file ;
    
    当多个用户同时同时使用同一个servlet时,

    将在所有HTTP请求之间共享,从而导致潜在的主要问题。摆脱它们并将它们移到doXxx()方法块内。