我正在尝试通过表格从最终用户获取输入。我使用jsp
。
欢迎。JSP
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<form action="welcome" method="post">
<input type="text" value="username" />
<input type="text" value="password" />
<input type="submit" value="login" />
</form>
</body>
</html>
用户将输入的信息将转到Servlet,将其打印到控制台。
myapp.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/welcome")
public class MyApp extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/welcome.jsp").forward(req, resp);
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("Name: " + name);
System.out.println("Password: " + password);
}
}
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_3_1.xsd"
id="WebApp_ID" version="3.1"
>
<servlet>
<servlet-name>MyApp</servlet-name>
<servlet-class>main.com.myfirstapp.MyApp</servlet-class>
</servlet>
</web-app>
在服务器上执行程序时,我会遇到问题。这是我遇到的错误
HTTP Status 405 - HTTP method GET is not supported by this URL
type: Status report
message: HTTP method GET is not supported by this URL
description: The specified HTTP method is not allowed for the requested resource.
我已经遇到了同样的问题,好吧,我建议您从动作中删除该斜线,然后让它仅<form action="welcome" method="post">
,因为您正在使用@Annotation,因此无需Web。.xml您可以将其删除。另一件事,您不会在您的servlet中获得等待结果,因为该表格中没有名称,这是一个示例您必须以表格键入String name = req.getParameter("name");
,必须设置像此 <input type="text" name="name" />
一样设置值的名称,而最终形式的同一件事看起来像
<form action="welcome" method="post">
<input type="text" name="name" />
<input type="text" name="passcode" />
<input type="submit" value="submit" />
</form>