我正在尝试使用java实现http重定向,一切都按预期工作,除非我第一次提交表单-请求以“待处理”状态发送-未调用httpHandler的handle函数。没有错误讯息。当我再次提交时-会调用handle,并且每条指令都可以正常工作。
我在多种设备和浏览器上进行了尝试。 这是html表单,我正在尝试使用add方法提交
<html><body><form method="POST">
First name:<br>
<input type="text" name="firstname" >
<br>
Last name:<br>
<input type="text" name="lastname" >
<br>
Age:<br>
<input type="text" name="age" >
<br><br>
<input type="submit" value="Submit" >
</form> </body></html>
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/students", new StudentController());
server.setExecutor(null);
server.start();
// StudentController class implements HttpHandler
public void handle(HttpExchange httpExchange) {
int id;
try {
String uri = httpExchange.getRequestURI().toString();
if (uri.equals("/students/add")) {
add(httpExchange);
} else {
index(httpExchange);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void index(HttpExchange httpExchange) throws IOException {
String response = getIndex();
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private void add(HttpExchange httpExchange) throws IOException {
String method = httpExchange.getRequestMethod();
if (method.equals("GET")) {
String response = getAdd();
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
}
if (method.equals("POST")) {
InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String formData = br.readLine();
Map inputs = parseFormData(formData);
int index = studentList.size();
String firstName = inputs.get("firstname").toString();
String lastName = inputs.get("lastname").toString();
int age = Integer.parseInt(inputs.get("age").toString());
Student student = new Student(index, firstName, lastName, age);
studentList.add(student);
br.close();
isr.close();
String url = "/students";
httpExchange.getResponseHeaders().set("Location", url);
httpExchange.sendResponseHeaders(303, -1);
}
}
我希望它在单击首次提交后避免等待处理的请求和运行处理程序。