![](/img/trans.png)
[英]“HTTP Status 405 – HTTP method GET is not supported by this URL” error when calling servlet from JSP
[英]Tomcat: Servlet sendRedirect to JSP says: “HTTP Status 405 - HTTP method GET is not supported by this URL”
下面是一個簡單的Servlet(Process.java),JSP頁面(index.jsp)和Model(Model.java)的代碼。
index.jsp :
<%@ page import="com.example.*" %>
<html>
<head>
<title> Myapp </title>
</head>
<body>
<form action="process.do" method="POST">
UserName: <input type="text" name="username">
<br>
UserID: <input type="text" name="userid">
<br>
<input type="submit">
<br>
<%
Model m = (Model) request.getAttribute("model");
if( m != null) {
out.println("Username: " + m.getUserName() );
out.println("UserID: " + m.getUserID() );
}
%>
</form>
</body>
</html>
Process.java :
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Process extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Model m = new Model();
m.setUserName( request.getParameter("username") );
m.setUserID( Integer.parseInt( request.getParameter("userid") ) );
request.setAttribute("model", m);
response.sendRedirect( request.getRequestURI() );
}
}
Model.java :
package com.example;
public class Model {
private String userName = "";
private int userID = -1;
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public int getUserID() {
return userID;
}
}
web.xml :
<servlet>
<servlet-name>Process</servlet-name>
<servlet-class>com.example.Process</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Process</servlet-name>
<url-pattern>/process.do</url-pattern>
</servlet-mapping>
我正在使用Tomcat7,並且已在上下文/ myapp中部署了此應用程序。 我能夠正確查看index.jsp頁面,但是在提交表單時,出現以下錯誤:
HTTP Status 405 - HTTP method GET is not supported by this URL
您正在嘗試使用response.sendRedirect( request.getRequestURI() );
?
這將指示瀏覽器向/process.do
發送一個GET請求,該請求在servlet中未處理(您僅擴展了doPost)。 如果您想返回index.jsp,只需添加response.sendRedirect( "index.jsp");
編輯:
因為您希望在index.jsp中訪問模型屬性,所以我們實際上無法進行瀏覽器重定向。 而是需要服務器重定向。
request.getRequestDispatcher("index.jsp").include(request, response)
而不是response.sendRedirect()
應該適合您。
您沒有重定向到JSP
。 讓我來解釋一下,當你發生了什么被post
的形式網址更改為http://domain.com/../process.do
,當你使用request.getRequestedUri()
它給Servlet的網址並沒有doGet()
方法,因此您遇到了該錯誤。 您應該使用response.sendRedirect("index.jsp")
重定向到index.jsp
文件。
當您使用“ response.sendRedirect()”方法時,它將請求對象移交給瀏覽器。因此,您將無法再處理請求對象。請使用“ RequestDispacther”代替“ sendRedirect”。希望如此可能會讓您更清楚。如果我沒有聯系到您,請別介意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.