gpt4 book ai didi

java - Tomcat Servlet 返回错误 405 - 此 URL 不支持 HTTP 方法 POST

转载 作者:行者123 更新时间:2023-11-28 23:56:22 28 4
gpt4 key购买 nike

我正在尝试在 Tomcat 7 上(在我的本地机器上)创建和部署一个简单的网络服务。它是一个 Java Servlet,用于将图像上传到服务器,将其存储在本地某个目录中,然后在我的 Servlet 中调用下游的另一个函数。

在尝试将图像发布到 servlet 时,我遇到了这个错误:

HTTP Status 405 - HTTP method POST is not supported by this URL
type Status report
message HTTP method POST is not supported by this URL
description The specified HTTP method is not allowed for the requested resource.

我关注了一些讨论同一问题的相关帖子,但我无法缩小问题范围。任何帮助将不胜感激。

我的源代码(带注释):

上传Servlet.java

package com.apps.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.apps.services.SearchByURL;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.File;
import java.io.OutputStream;

public class UploadServlet extends HttpServlet {
private String filePath;
private File file;
private String bestGuessString;

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
bestGuessString = "";

filePath = getServletContext().getInitParameter("file-upload");
System.out.println("filePath: " + filePath);
filePath = getServletContext().getRealPath(filePath);
System.out.println("filePath2: " + filePath);

String fileName = "";
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
OutputStream outputStream = null;

if (item.isFormField()) {
System.out.println("Got a form field: "
+ item.getFieldName());
} else {
System.out.println("Got an uploaded file: "
+ item.getFieldName() + ", name = "
+ item.getName());
fileName = item.getName();
System.out.println("Absolute path: " + filePath + "/"
+ fileName);

outputStream = new FileOutputStream(new File(fileName));
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
response.getOutputStream().write(buffer, 0, len);
outputStream.write(buffer, 0, len);
}
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}

//Downstream logic (I am using the image and passing it to another custom class)
//CustomClass.java is defined separately
String finalGuess = CustomClass.customFunction(fileName);
if (finalGuess.equals(""))
bestGuessString = "Sorry! Google did not find the image interesting enough.. :)";
else
bestGuessString = finalGuess;

//Redirecting the response to doGet and printing the final result there
response.sendRedirect("/UploadServlet?imageUrl=" + bestGuessString);
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String imageUrl = request.getParameter("imageUrl");
response.setHeader("Content-Type", "text/html");
System.out.println("in doGet(), imageUrl: " + imageUrl);
response.getWriter().println("Best Guess: " + bestGuessString);
}

public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
}

网络.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.apps.servlets.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<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>
data
</param-value>
</context-param>
</web-app>

index.html

<!doctype html> 
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form
action="UploadServlet" method="post" enctype="multipart/form-data"> <input
type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload
File" /> </form>
</body>
</html>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.apps.innovative</groupId>
<artifactId>VoyagerServices</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>VoyagerServices Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0-alpha4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.apache.james</groupId>
<artifactId>apache-mime4j</artifactId>
<version>0.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>

<build>
<plugins>
<!-- Maven Tomcat Plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<url>http://127.0.0.1:8080/manager/html</url>
<server>TomcatServer</server>
<path>/VoyagerServices</path>
<username>admin</username>
<password>password</password>
</configuration>
</plugin>
<!-- Maven compiler plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

最佳答案

**html code**

<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="upload" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>


**servlet code**

package servlet;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
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(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

private final static Logger LOGGER
= Logger.getLogger(FileUploadServlet.class.getCanonicalName());

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

// Create path components to save the file
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);

OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();

try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();

int read = 0;
final byte[] bytes = new byte[1024];

while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());

LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}

private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}


**Also Check this Link**

http://multiplejava.blogspot.in/2015/03/upload-files-to-server-via-java-servlet.html

[另请检查此链接]

关于java - Tomcat Servlet 返回错误 405 - 此 URL 不支持 HTTP 方法 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24232745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com