我正在尝试从html获取值,但它只是使用Post或Get命令赋予null。我也在使用Wildfly Application Server。当我提交它进入下一页但值似乎为'null'。
PS:我在xml文件中添加了servlet,如下所示:
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/dataServlet</url-pattern>
</servlet-mapping>
的Servlet
package webpackage;
import java.io.IOException;
import java.io.PrintWriter;
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("/dataServlet")
public class DataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Get
String combobox=request.getParameter("User");
String value=request.getParameter("demo");
PrintWriter writer = response.getWriter();
// Build
String htmlRespone = "<html>";
htmlRespone += "<h2>User Id: " + combobox + "</h2>";
htmlRespone += "<h2>User Id: " + value + "</h2>";
htmlRespone += "</html>";
// Return
writer.println(htmlRespone);
System.out.println(combobox);
}
}
HTML:
<select name="User">
<option selected="true" value="Example1">User1</option>
<option value="Example2">User2</option>
</select>
<form method="post" action="dataServlet">
<button type="submit">Change</button>
</form>
<h1></h1>
<p id="demo">Example3</p>
答案 0 :(得分:3)
对于<form>
User
之内
<form method="post" action="dataServlet">
<select name="User">
<option selected="true" value="Example1">User1</option>
<option value="Example2">User2</option>
</select>
<button type="submit">Change</button>
</form>
<h1></h1>
<p id="demo">Example3</p>
这是必要的name
属性(demo
),请注意,这不会对<p>
起作用,但您可以使用隐藏输入以在表单中设置值。
PS:小心,你应该使用相同的语法,一旦你以大写开头,然后使用小写User
demo
EDI: 一个w3schools form guide