我收到一个错误,我不知道为什么。我有这个项目:
当我执行registro.html时,效果很好:
但是当我在代码中提交帖子时,我认为它没有到达Registro.java
registro.html中的代码是:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="http://localhost:8080/Ejer2/Registro.java" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
在Registro.java中:
package Ejer2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
@SuppressWarnings("deprecation")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
问题是什么?
最佳答案
您不能直接在html Registro.java
内部使用或调用action
,而是需要映射Registro
servlet类的url模式,如下所示:
@WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
//Add your code here
}
现在,将上面配置的
urlPattern
用作action
中的registro.html
,如下所示:<form action="/Registro" method="POST">
另外,另一个要点是,对于servlet类,通常不需要
SingleThreadModel
(因为所有请求都将使用同一servlet实例进行处理),但是如果您故意使用SingleThreadModel
,则可以离开照原样。