有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从servlet检索请求属性?

我正在创建一个基本网站,在那里你可以向数据库中添加产品。问题是在填写表单以在JSP文件中添加产品时。我可以提交表单,但无法从servlet中检索到响应。一旦表格提交,表格将再次为空。这种情况会反复发生,除非我强制发生FormatNumberException。我一直在找,但还没找到解决办法

提前感谢你的帮助

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    Ingrese un producto
    <hr>
    <% if(request.getAttribute("mensaje")!= null){
        out.print(request.getAttribute("mensaje"));
        }
    %>
    <form action="IngresarServlet" method="POST">
        Descripción: <input type="text" name="descr"/><br>
        Precio: <input type="text" name="precio"/><br>
        <input type="submit" value="enviar">
    </form>

</body>

@WebServlet(name = "IngresarServlet", urlPatterns = {"/IngresarServlet"})
public class IngresarServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String descripcion = request.getParameter("descr");
        Double precio = Double.valueOf(request.getParameter("precio"));

        Producto p = new Producto(descripcion, precio);

        ProductoDAO dao = new ProductoDAO();
        try {
            dao.insertar(p);
            request.setAttribute("mensaje", "El producto se ha insertado correctamente.");
        } catch (Exception ex) {
            request.setAttribute("mensaje", ex.getMessage());
        }
        request.getRequestDispatcher("Ingresar.jsp").forward(request, response);
    }
}

共 (0) 个答案