简体   繁体   中英

Getting value from combobox to servlet in jsp

I have problem with get a value from combobox in my .jsp file to servlet. I use method request.getParameter i other servlets and it works. In this class it don't. I was also trying to get value from text field to this servlet but also don't work. I don't have any idea how to solve this problem.

I have combobox like that:

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

I'm tring to get value:

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

My jsp file

<!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>

And my servlet file

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

It's because you're sending a multipart/form-data request while that's by default not supported by servlets. I however notice that you're still using the "legacy" Apache Commons FileUpload to obtain the uploaded file instead of new Servlet 3.0 provided HttpServletRequest#getPart() . In that case, you've basically 2 options:

  1. Stick to Commons FileUpload. You should be collecting regular form fields in the else block of your if (!fi.isFormField()) which you're currently completely ignoring.

     if (!fi.isFormField()) { // Collect uploaded file from fi. } else { // Collect normal form field from fi. } 
  2. Get rid of Commons FileUpload and use @MultipartConfig annotation.

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

    This way you can get files by request.getPart() and keep using request.getParameter() the usual way for regular form fields.

See also:


Unrelared to the concrete problem, that's not a combobox, but that's a dropdown. A combobox is an editable dropdown. Further, writing Java code in JSP is a bad practice. Java code belongs in Java classes like a servlet. To loop over options, use JSTL <c:forEach> . And, writing HTML code in a Java class like a servlet is a bad practice. HTML code belongs in a JSP file. Use RequestDispatcher#forward() to present results in a JSP. See further also our servlets wiki page .

Oh, you've a major threadsafety problem in your servlet. There's only one instance of a servlet during applications lifetime which is shared across all HTTP requests. Those fields

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

would be shared across all HTTP requests resulting in potential major problems when multiple users concurrently use the same servlet at the same moment. Get rid of them and move them to inside the doXxx() method block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM