【发布时间】:2017-02-04 12:04:07
【问题描述】:
所以我在前端 Web 开发方面有一些经验,并且在 OOP(使用 Java)方面有很多经验,但我从来没有处理过来自 HTML 表单的用户输入以及对这些数据进行处理的工作。由于我在 Java 方面有如此多的经验,我认为这将是最好的语言。我想做的是从表单中收集用户数据(基本的东西:姓名、地址等)并在 Java 文件中处理它。现在,我认为数据甚至没有被发送到 Java 文件,因为当我单击“提交”按钮时,什么也没有发生。我在这里做错了什么?
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content = "IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Lob Application</title>
<link href = "bootstrap.min.css" rel = "stylesheet">
<link href = "stylesheet.css" rel = "stylesheet" >
</head>
<body>
<div id = formInput class = "container-fluid">
<form name = "submitDataForm" method = "post" action = "processData">
Name:<br>
<input type = "text" name = "name"><br>
Address Line 1:<br>
<input type = "text" name = "addressLineOne"><br>
Address Line 2:<br>
<input type = "text" name = "addressLineTwo"><br>
City:<br>
<input type = "text" name = "city"><br>
State:<br>
<input type = "text" name = "state"><br>
Zip Code:<br>
<input type = "text" name = "zip"><br>
Message:<br>
<input type = "text" name = "message"><br>
<input id = "submit" type = "submit" value = "Submit"
</form>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
</body>
</html>
processData.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/processData")
public class processData extends HttpServlet{
public static void main(String[] args){}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
String name = req.getParameter("name");
String address1 = req.getParameter("addressLineOne");
String address2 = req.getParameter("addressLineTwo");
String city = req.getParameter("city");
String state = req.getParameter("state");
String zip = req.getParameter("zip");
String message = req.getParameter("message");
System.out.println("city: " + city);
PrintWriter writer = resp.getWriter();
String htmlResponse = "<html>";
htmlResponse += "<h2>Your city is: " + city +"<br/>";
htmlResponse += "</html>";
writer.println(htmlResponse);
}
}
【问题讨论】:
-
检查浏览器控制台是否有任何错误以及网络选项卡是否发送请求。
-
我该怎么做,我不确定这两个是什么意思:/
-
如果您使用的是 chrome,然后单击三个垂直点图标,用于打开设置。将在此打开一个窗口,转到更多工具并选择开发人员工具。将打开一个新窗口。在此选择控制台选项卡中。在这里打印所有错误消息。还有网络选项卡,显示从浏览器发送的所有请求。
-
你是如何运行这个程序的? Servlet 本身不能工作,它们需要在 Web 服务器中运行。
-
@immibis 现在我只是通过在 Chrome 中打开 index.html 在我的 PC 上本地运行它。当我单击提交按钮时,没有任何反应。