HTTP 404在tomcat 8.0.5中请求的资源不可用错误

时间:2015-10-02 05:52:47

标签: java tomcat servlets

我目前正在通过servlet上传文件,我收到404错误。这是我的代码

FileUpload.html

<html>
    <head>
        <title>File Uploading Form</title>
    </head>
    <body>
        <h3>File Upload:</h3>
        Select a file to upload: 
        <br />
        <!-- form tag is genraly used for user input-->
        <!-- action attr defines action to be performed when form is submitted -->
        <!-- method attr defines the HTTP method to be used when submitting forms -->
        <!-- enctype attr specifies the encoding of the submitted data -->
        <form action="UploadServlet" method="post" enctype="multipart/form-data"> 
        <!-- size attr specifies the visible width in chars of an <input> element -->
        <input type="file" name="file" size="50" />
        <br />
        <input type="submit" value="Upload File" />
        </form>
    </body>
</html>

我已更新我的web.xml文件,如下所示

<context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>c:\apache-tomcat-5.5.29\webapps\data\</param-value> 
</context-param>
<servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

UploadServlet.java //导入所需的java库

import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
    boolean isMultipart;
    private String filePath;
    private int maxFileSize = 50 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file ;
    public void init( ){
       // Get the file location where it would be stored.
       filePath = 
         getServletConfig().getInitParameter("file-upload"); 
    }
    public void doPost(HttpServletRequest request, 
           HttpServletResponse response)
          throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
     PrintWriter out = response.getWriter( );
     if( !isMultipart ){
     out.println("<html>");
     out.println("<head>");
     out.println("<title>Servlet upload</title>");  
     out.println("</head>");
     out.println("<body>");
     out.println("<p>No file uploaded</p>"); 
     out.println("</body>");
     out.println("</html>");
     return;
  }
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // maximum size that will be stored in memory
  factory.setSizeThreshold(maxMemSize);
  // Location to save data that is larger than maxMemSize.
  factory.setRepository(new File("c:\\temp"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );

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

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

  out.println("<html>");
  out.println("<head>");
  out.println("<title>Servlet upload</title>");  
  out.println("</head>");
  out.println("<body>");
  while ( i.hasNext () ) 
  {
     FileItem fi = (FileItem)i.next();
     if ( !fi.isFormField () )  
     {
        // Get the uploaded file parameters
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        String contentType = fi.getContentType();
        boolean isInMemory = fi.isInMemory();
        long sizeInBytes = fi.getSize();
        // Write the file
        if( fileName.lastIndexOf("\\") >= 0 ){
           file = new File( filePath + 
           fileName.substring( fileName.lastIndexOf("\\"))) ;
        }else{
           file = new File( filePath + 
           fileName.substring(fileName.lastIndexOf("\\")+1)) ;
        }
        fi.write( file ) ;
        out.println("Uploaded Filename: " + fileName + "<br>");
     }
  }
  out.println("</body>");
  out.println("</html>");
  }catch(Exception ex) {
   System.out.println(ex);
 }
 }
 public void doGet(HttpServletRequest request, 
                   HttpServletResponse response)
    throws ServletException, java.io.IOException {

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

3 个答案:

答案 0 :(得分:0)

您需要提供contextPath以正确引用Servlet URL,我的意思是您的表单的操作属性必须为<form action="/AppContext/UploadServlet" ...

如果您使用JSP或其他内容,而不是纯HTML,您可以使用一些scriptlet或jstl以编程方式检索上下文路径,例如:

<form action="<%=request.getContextPath()%>/UploadServlet" ...

<form action="${pageContext.request.contextPath}/UploadServlet" ...

希望它有所帮助!

答案 1 :(得分:0)

可能是因为你的项目结构,请检查以下几件事。

 $CATALINA_HOME
 |
 |__webapps
      |
      |___FileUploadProj
              |
              |
              |______WEB-INF
              |         |__classes
              |         |    |__UploadServlet.class
              |         |
              |         |__src
              |         |   |___UploadServlet.java
              |         |
              |         |__lib
              |         |   |___*.jar
              |         |
              |         |__web.xml
              |
              |_____FileUpload.html
              |
              |_____css,images, scripts
  • 将您的java UploadServlet.java保存在src文件夹下。
  • 一旦你压缩java文件,复制UploadServlet.class文件并将其保存在classes文件夹下。 (我怀疑这可能是您的问题,每次更改.class文件时都不要忘记复制.java文件)
  • web.xml保留在WEB-INF文件夹
  • 将FileUpload.html放在WEB-INF
  • 之外

一旦确定了上述内容,请试一试。

答案 2 :(得分:0)

我尝试使用您提供的代码,当我上传一个文件时,它返回响应为:

上传文件名:image01.jpg

我怀疑你打包应用程序进行部署的方式。@ Uppicharla提供的是正确的。

我部署如下:

webapps\
        TestUpload\
                  index.html

                   WEB-INF\
                           classes\UploadServlet.class
                           lib\commons-fileupload-1.3.jar,commons-io-2.4.jar
                           web.xml

TestUpload是我的应用程序名称,index.html是我的上传html。 我使用的web.xml是:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>TestUpload</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <context-param>
        <description>Location to store uploaded file</description>
        <param-name>file-upload</param-name>
        <param-value>G:\apache-tomcat-7.0.37\webapps\data\</param-value>
    </context-param>
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>
</web-app>

请试试这个。

注意:我尝试使用带有servlet规范2.5的 7

还有一件事,你正在使用tomcat 8吗?但是在你的web.xml中你指定了一个tomcat 5的路径