2017-10-09 108 views
0

我試圖讓我的頁面允許用戶將文件上傳到他們的計算機上。連接index.htmlHelloServlet.java是我正在努力。我Tomcat工作正常,因爲我得到errorsTerminal這很好,因爲它顯示它連接到我的項目。爲什麼我的本地主機中的tomcat不能在Eclipse中正確運行?

我只是不明白這是如何工作。當我點擊運行時,我希望index.html頁面出現在Eclipse標籤之一中,允許我將文件上傳到我的電腦。我怎樣才能解決這個問題?

每次我在Eclipserun我得到這些errorsTerminalpic of error in Eclipse)

08-Oct-2017 16:00:01.872 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 999 ms 
08-Oct-2017 16:00:01.979 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina] 
08-Oct-2017 16:00:01.980 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.23 
08-Oct-2017 16:00:01.993 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/docs] 
08-Oct-2017 16:00:02.609 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/docs] has finished in [615] ms 
08-Oct-2017 16:00:02.610 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/examples] 
08-Oct-2017 16:00:03.130 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/examples] has finished in [520] ms 
08-Oct-2017 16:00:03.131 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/hello] 
08-Oct-2017 16:00:03.189 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/hello] has finished in [58] ms 
08-Oct-2017 16:00:03.189 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/host-manager] 
08-Oct-2017 16:00:03.232 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/host-manager] has finished in [43] ms 
08-Oct-2017 16:00:03.233 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/manager] 
08-Oct-2017 16:00:03.271 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/manager] has finished in [38] ms 
08-Oct-2017 16:00:03.272 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Applications/tomcat/webapps/ROOT] 
08-Oct-2017 16:00:03.318 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Applications/tomcat/webapps/ROOT] has finished in [45] ms 
08-Oct-2017 16:00:03.322 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"] 
08-Oct-2017 16:00:03.330 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 1457 ms 
09-Oct-2017 07:40:36.569 WARNING [main] org.apache.catalina.core.StandardServer.await StandardServer.await: Invalid command 'GET /FileUploadServlet/index.html HTTP/1.1' received 
09-Oct-2017 07:40:36.674 WARNING [main] org.apache.catalina.core.StandardServer.await StandardServer.await: Invalid command 'GET /FileUploadServlet/index.html HTTP/1.1' received 
09-Oct-2017 07:40:36.779 WARNING [main] org.apache.catalina.core.StandardServer.await StandardServer.await: Invalid command 'GET /FileUploadServlet/index.html HTTP/1.1' received 
09-Oct-2017 07:40:57.556 WARNING [main] org.apache.catalina.core.StandardServer.await StandardServer.await: Invalid command 'GET /FileUploadServlet/index.html HTTP/1.1' received 

這裏的index.html

<html> 
<head></head> 
<body> 
<form action="FileUploadServlet" method="post" enctype="multipart/form-data"> 
Select File to Upload:<input type="file" name="fileName"> 
<br> 
<input type="submit" value="Upload"> 
</form> 
</body> 
</html> 

這裏是FileUploadServlet.java

package net.techsuite.SIPPA_HealthTech; 
//package com.journaldev.servlet; 

import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 

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

@WebServlet("/FileUploadServlet") 
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB 
       maxFileSize=1024*1024*50,   // 50 MB 
       maxRequestSize=1024*1024*100)  // 100 MB 
public class FileUploadServlet extends HttpServlet { 

    private static final long serialVersionUID = 205242440643911308L; 

    /** 
    * Directory where uploaded files will be saved, its relative to 
    * the web application directory. 
    */ 
    private static final String UPLOAD_DIR = "uploads"; 

    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // gets absolute path of the web application 
     String applicationPath = request.getServletContext().getRealPath(""); 
     // constructs path of the directory to save uploaded file 
     String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; 

     // creates the save directory if it does not exists 
     File fileSaveDir = new File(uploadFilePath); 
     if (!fileSaveDir.exists()) { 
      fileSaveDir.mkdirs(); 
     } 
     System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath()); 

     String fileName = ""; 
     //Get all the parts from request and write it to the file on server 
     for (Part part : request.getParts()) { 
      fileName = getFileName(part); 
      File file = new File(fileName); 
      part.write(uploadFilePath + File.separator + file.getName()); 
     } 
     writeToResponse(response, "File uploaded successfully to: " + uploadFilePath); 

     request.setAttribute("message", "File uploaded successfully!"); 
     getServletContext().getRequestDispatcher("/response.jsp").forward(
       request, response); 

    } 

    /** 
    * Utility method to get file name from HTTP header content-disposition 
    */ 
    private String getFileName(Part part) { 
     String contentDisp = part.getHeader("content-disposition"); 
     System.out.println("content-disposition header= "+contentDisp); 
     String[] tokens = contentDisp.split(";"); 
     for (String token : tokens) { 
      if (token.trim().startsWith("filename")) { 
       return token.substring(token.indexOf("=") + 2, token.length()-1); 
      } 
     } 
     return ""; 
    } 


    private void writeToResponse(HttpServletResponse resp, String results) throws IOException { 
     PrintWriter writer = new PrintWriter(resp.getOutputStream()); 
     resp.setContentType("text/plain"); 

     if (results.isEmpty()) { 
      writer.write("No results found."); 
     } else { 
      writer.write(results); 
     } 
     writer.close(); 
    } 


} 

這裏的web.xml文件夾WebContent

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 
    <display-name>FileUploadServlet</display-name> 
    <welcome-file-list> 
    <welcome-file>index.html</welcome-file> 
    <welcome-file>index.htm</welcome-file> 
    <welcome-file>index.jsp</welcome-file> 
    <welcome-file>default.html</welcome-file> 
    <welcome-file>default.htm</welcome-file> 
    <welcome-file>default.jsp</welcome-file> 
    </welcome-file-list> 
</web-app> 

這裏的server.xml文件:

<?xml version="1.0" encoding="UTF-8"?> 
<!-- 
    Licensed to the Apache Software Foundation (ASF) under one or more 
    contributor license agreements. See the NOTICE file distributed with 
    this work for additional information regarding copyright ownership. 
    The ASF licenses this file to You under the Apache License, Version 2.0 
    (the "License"); you may not use this file except in compliance with 
    the License. You may obtain a copy of the License at 

     http://www.apache.org/licenses/LICENSE-2.0 

    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License. 
--><!-- Note: A "Server" is not itself a "Container", so you may not 
    define subcomponents such as "Valves" at this level. 
    Documentation at /docs/config/server.html 
--><Server port="8005" shutdown="SHUTDOWN"> 
    <Listener className="org.apache.catalina.startup.VersionLoggerListener"/> 
    <!-- Security listener. Documentation at /docs/config/listeners.html 
    <Listener className="org.apache.catalina.security.SecurityListener" /> 
    --> 
    <!--APR library loader. Documentation at /docs/apr.html --> 
    <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/> 
    <!-- Prevent memory leaks due to use of particular java/javax APIs--> 
    <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/> 
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/> 
    <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/> 

    <!-- Global JNDI resources 
     Documentation at /docs/jndi-resources-howto.html 
    --> 
    <GlobalNamingResources> 
    <!-- Editable user database that can also be used by 
     UserDatabaseRealm to authenticate users 
    --> 
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/> 
    </GlobalNamingResources> 

    <!-- A "Service" is a collection of one or more "Connectors" that share 
     a single "Container" Note: A "Service" is not itself a "Container", 
     so you may not define subcomponents such as "Valves" at this level. 
     Documentation at /docs/config/service.html 
    --> 
    <Service name="Catalina"> 

    <!--The connectors can use a shared executor, you can define one or more named thread pools--> 
    <!-- 
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
     maxThreads="150" minSpareThreads="4"/> 
    --> 


    <!-- A "Connector" represents an endpoint by which requests are received 
     and responses are returned. Documentation at : 
     Java HTTP Connector: /docs/config/http.html 
     Java AJP Connector: /docs/config/ajp.html 
     APR (HTTP/AJP) Connector: /docs/apr.html 
     Define a non-SSL/TLS HTTP/1.1 Connector on port 8080 
    --> 
    <Connector connectionTimeout="20000" port="8005" protocol="HTTP/1.1" redirectPort="8443"/> 
    <!-- A "Connector" using the shared thread pool--> 
    <!-- 
    <Connector executor="tomcatThreadPool" 
       port="8080" protocol="HTTP/1.1" 
       connectionTimeout="20000" 
       redirectPort="8443" /> 
    --> 
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 
     This connector uses the NIO implementation. The default 
     SSLImplementation will depend on the presence of the APR/native 
     library and the useOpenSSL attribute of the 
     AprLifecycleListener. 
     Either JSSE or OpenSSL style configuration may be used regardless of 
     the SSLImplementation selected. JSSE style configuration is used below. 
    --> 
    <!-- 
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" 
       maxThreads="150" SSLEnabled="true"> 
     <SSLHostConfig> 
      <Certificate certificateKeystoreFile="conf/localhost-rsa.jks" 
         type="RSA" /> 
     </SSLHostConfig> 
    </Connector> 
    --> 
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2 
     This connector uses the APR/native implementation which always uses 
     OpenSSL for TLS. 
     Either JSSE or OpenSSL style configuration may be used. OpenSSL style 
     configuration is used below. 
    --> 
    <!-- 
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol" 
       maxThreads="150" SSLEnabled="true" > 
     <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> 
     <SSLHostConfig> 
      <Certificate certificateKeyFile="conf/localhost-rsa-key.pem" 
         certificateFile="conf/localhost-rsa-cert.pem" 
         certificateChainFile="conf/localhost-rsa-chain.pem" 
         type="RSA" /> 
     </SSLHostConfig> 
    </Connector> 
    --> 

    <!-- Define an AJP 1.3 Connector on port 8009 --> 
    <Connector port="8008" protocol="AJP/1.3" redirectPort="8443"/> 


    <!-- An Engine represents the entry point (within Catalina) that processes 
     every request. The Engine implementation for Tomcat stand alone 
     analyzes the HTTP headers included with the request, and passes them 
     on to the appropriate Host (virtual host). 
     Documentation at /docs/config/engine.html --> 

    <!-- You should set jvmRoute to support load-balancing via AJP ie : 
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> 
    --> 
    <Engine defaultHost="localhost" name="Catalina"> 

     <!--For clustering, please take a look at documentation at: 
      /docs/cluster-howto.html (simple how to) 
      /docs/config/cluster.html (reference documentation) --> 
     <!-- 
     <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
     --> 

     <!-- Use the LockOutRealm to prevent attempts to guess user passwords 
      via a brute-force attack --> 
     <Realm className="org.apache.catalina.realm.LockOutRealm"> 
     <!-- This Realm uses the UserDatabase configured in the global JNDI 
      resources under the key "UserDatabase". Any edits 
      that are performed against this UserDatabase are immediately 
      available for use by the Realm. --> 
     <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> 
     </Realm> 

     <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> 

     <!-- SingleSignOn valve, share authentication between web applications 
      Documentation at: /docs/config/valve.html --> 
     <!-- 
     <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
     --> 

     <!-- Access log processes all example. 
      Documentation at: /docs/config/valve.html 
      Note: The pattern used is equivalent to using pattern="common" --> 
     <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/> 

     <Context docBase="FileUploadServlet" path="/FileUploadServlet" reloadable="true" source="org.eclipse.jst.jee.server:FileUploadServlet"/></Host> 
    </Engine> 
    </Service> 
</Server> 
+0

您是否正確地完成了部署描述符中的映射? –

+0

@robot_alien不知道,我該怎麼做? (nice name btw) – obsolutemal

+0

'@WebServlet(「/ FileUploadServlet」)。/我們還需要映射@robot_alien – Optional

回答

0

<Server port="8005" shutdown="SHUTDOWN">是錯誤的原因。您正在關閉端口上調用index.html。

應與下面的連接器不同。

<Connector connectionTimeout="20000" port="8005" protocol="HTTP/1.1" redirectPort="8443"/>

改變,要e.g

<Connector address="0.0.0.0" connectionTimeout="20000" port="8009" protocol="HTTP/1.1" redirectPort="8443"/>

還要檢查是否存在由8005所佔用的端口,看看爲什麼?殺死進程,如果有的話。

+0

我在哪裏可以找到適合我的情況的地址? – obsolutemal

+0

只是兩者不一樣。只需添加8009並運行即可嘗試。那麼你的端口將是8009 – Optional

+0

好吧,試試吧,告訴你發生了什麼。 – obsolutemal

相關問題