将发布数据从JSP发送到Java Servlet [英] Sending post data from JSP to a Java Servlet
问题描述
我正在尝试将数据从JSP文件发送到Java Servlet.我在这里看到了很多有关如何执行此操作的示例,并且我相信我的方法是正确的,但是由于某些原因,未在我的servlet中调用doPost()方法.
I am trying to send data from a JSP file to a Java Servlet. I've seen so many examples on here on how to do it, and I believe I am doing it the right way, but for some reason the doPost() methods is not being called inside my servlet.
这是我添加到我的web.xml文件中的内容:
Here is what I added to my web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>src.action.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
这是我的JSP文件
<html>
<head>
</head>
<body>
<form action = "localhost:8080/UserModule/src/action/login" method="post">
Username<input type = "text" name = "username"><br><br>
Password<input type = "password" name = "password"><br><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
这是我的Java servlet:
Here is my Java servlet:
package action;
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;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = (request.getAttribute("username")).toString();
System.out.println("asd");
String password = (String) request.getAttribute("password");
System.out.println(username);
}
}
在import javax.servlet.annotation.WebServlet;
和@WebServlet("/login")
这是因为它们仅在规范v3.0中实现,而我只被允许使用规范v2.5(在工作中必需). 有谁知道如何解决这个问题?
It's because they were only implemented in the spec v3.0, while I am only allowed to use spec v2.5 (required to at work). Anyone has any idea how to solve this issue?
我的目录:
推荐答案
我可以在您的帖子中看到多个错误,
I could see multiple errors in your post ,
-
将动作属性替换为,
Replace the action attribute with ,
<form action = "./login" method="post">
如果您使用的是2.5版,请删除导入的注释以及这一行,
If your using the version 2.5 , remove the import for annotation and also this line,
@WebServlet("/login")
Thirdly, to access the <form>
elements in the servlet , use request#getParameter
String username = request.getParameter("username"));
这篇关于将发布数据从JSP发送到Java Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!