我的 servlet
有问题。我有一个 HTML 页面,当我提交表单时,我调用 get 方法来获取两个数字的总和,但出现错误。但我已经在我的 servlet
类中声明了 get 方法。
类型:状态报告
消息:此 URL 不支持 HTTP 方法 POST
描述源服务器已知请求行中接收到的方法,但目标资源不支持。
Servlet 代码:
public class AddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
int a=Integer.parseInt(req.getParameter("num1"));
int b=Integer.parseInt(req.getParameter("num2"));
int sum=a+b;
resp.getWriter().println(sum+ " doGet method");
}
}
html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet</title>
</head>
<body>
<form action="add" method="get" >
Enter 1st number<input type="text" name="num1">
Enter 2st number<input type="text" name="num2">
<input type="submit">
</form>
</body>
</html>
部署描述符代码: web.xml
<?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_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>ServletPractice1</display-name>
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.meet.servlet.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
最佳答案
您没有有效的 doGet() 方法,当您直接在地址栏中输入 servlet 的路径时,像 Tomcat 这样的 Web 容器将尝试调用 doGet() 方法。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{
....
}
或者像这样重写服务方法:
protected 无效服务(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException { doPost(请求,响应); }
关于java - http方法在servlet中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460704/