【问题标题】:How can i show and keep a variable when redirecting back and forth from an html to a jsp page and a jsp page to an html?从 html 到 jsp 页面以及从 jsp 页面到 html 来回重定向时,如何显示和保留变量?
【发布时间】:2016-06-10 15:43:26
【问题描述】:

我正在使用 servlet 猜测数字应用程序,当我输入一个数字并按下“猜测按钮”时,它会将我发送到一个 jsp 页面并告诉我数字是否太低、太高或我猜到了它正确。我的 jsp 页面中有一个链接,可以让我回到 html 页面再次猜测。

我的问题是,当我从 html 页面来回返回到我的 jsp 页面时,我如何保留我需要猜测的生成数字,以便我可以继续猜测相同的数字?例如,如果我需要猜测的数字是 50,并且我按下“猜测按钮”并将我带到 jsp,无论结果如何,我如何保留该数字直到我关闭网页? (注意:当我使用 <%= session.getAttribute("numero") %> 时,我得到 NULL)

这是我的代码:

package numero;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Eddy
 */

@WebServlet(name = "Controlador", urlPatterns = {"/Adivina"})
public class Controlador extends HttpServlet {
    @EJB
    Generador generar;

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

        response.setContentType("text/html;charset=UTF-8");       

        String compartir = "compartir";
        request.setAttribute("compartirID", compartir); // add to request
        request.getSession().setAttribute("compartirID", compartir); // add to session
        this.getServletConfig().getServletContext().setAttribute("compartirID", compartir); // add to application context
        request.getRequestDispatcher("/Adivina").forward(request, response);
    }//http se contituye por transacciones

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

        //recupera información enviada por el cliente
        String numero = request.getParameter("numero");
        double valor = Double.parseDouble(numero);

        //envía al modelo para procesamiento
        String[] num = generar.numero(valor);

        //redirecciona a la vista
        request.setAttribute("resultado", num);
        request.getRequestDispatcher("/mostrar.jsp").forward(request,response);
    }

}

这是我的html:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->

<html>
    <head>
        <title>Adivina el Numero</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Adivina el Numero!</h1>
        <h2>Ingrese un numero del 1 al 100</h2>
        <form method="POST" action="Adivina">
            Ingrese el numero: <input type="text" name="numero"/></br>
            <input type="submit" value="Adivina"/></br>

        </form>

    </body>
</html>

这是我的jsp:

<%@page import="java.text.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>
        <title>Adivinar</title>
    </head>
    <body>
        <h3>Bienvenido</h3>
        <%= session.getAttribute("numero") %>
        <table>   
            <% 
                String[] resultado = (String[])request.getAttribute("resultado");
                for(String str : resultado) { 
            %>
            <tr>
                <td bgcolor='#CCCCCC'>
                    <%= str %>
                </td>
            </tr>
            <% 
                }
            %>
        </table>
        <a href="adivina.html">Regresar</a>
    </body>
</html>

这是我的号码生成类:

package numero;

/**
 *
 * @author Eddy
 */

import javax.ejb.Stateless;

@Stateless
public class Generador {

    public String[] numero(double numero) {
        double x = 0;
        double y = 0;
        x = (Math.random() * 100)+1;
        x = Math.floor(x);

        /*y = (Math.random() * x)+1;
        y = Math.floor(y);

        x+=x;

        System.out.println("x=" + x);
        System.out.println("y=" + y);*/

        if(numero>=1 && numero<=100)
        {       
            if(numero>x)
            {
                return new String[] {"Muy Alto"};
            }
            else if(numero<x)
            {    
                return new String[] {"Muy Bajo"};
            }
            else if(numero==x)
            {
                return new String[] {"Adivinó"};
            }
        }
        else
        {
            return new String[] {"Ingrese un numero dentro del rango"};
        }    
        return null;
    }
}

【问题讨论】:

    标签: java html jsp servlets


    【解决方案1】:

    我认为问题是: 当您想将其与用户的输入进行比较时,您会生成一个新数字 解决方案是将生成的数字分开并将其放入 Controlador 类中的属性中,如下所示:

    public class Controlador extends HttpServlet {
    private double x;
    ...
    }
    

    并在 servlet 中添加一个生成数字的过程 公共类 Controlador 扩展 HttpServlet {

    public void generate(){
     x = 0;
    
            x = (Math.random() * 100)+1;
            x = Math.floor(x);
    
     }
    

    然后在会话中设置生成的值

    request.getSession().setAttribute("Val",generated_Value); 
    

    然后在函数中传递两个属性

    generar.numero(valor,generated_Value);
    

    当你要返回用户浏览的页面时,这必须是jsp页面(而不是html) 您将生成的值保存在隐藏输入中的位置

    最后试试这段代码:

     public class Controlador extends HttpServlet {
    
        private double x;
    
            @EJB
            Generador generar;
    
    
            public void generate(){
             x = 0;
    
                    x = (Math.random() * 100)+1;
                    x = Math.floor(x);
    
             }
    
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
    
    
            }
    
            @Override
            protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
    
                String generatedVal = request.getParameter("genVAL");
                Double d = Double.parseDouble(generatedVal); 
                if(generatedVal==null){
                 generate();
    
                 d=x;
                }
    
    
                String numero = request.getParameter("numero");
                double valor = Double.parseDouble(numero);
    
                //envía al modelo para procesamiento
                String num = generar.numero(valor,d);
    
                //redirecciona a la vista
                request.getSession().setAttribute("Val",d); 
                request.setAttribute("resultado", num);
                request.setAttribute("numero", numero);
    
    request.getRequestDispatcher("/mostrar.jsp").forward(request,response);
            }
    
        }
    

    在此之后将 html 更改为 jsp 并将其放入表单中:

    <form method="POST" action="Adivina">
                Ingrese el numero: <input type="text" name="numero"/></br>
                <input type="hidden" name="genVAL" value="${Val}"/>
                <input type="submit" value="Adivina"/></br>
    
            </form>
    

    并将函数 numero 更改为 numero(double numero,double x)

    @Stateless
    public class Generador {
    
        public String numero(double numero,double x) {
    
    
            if(numero>=1 && numero<=100)
            {       
                if(numero>x)
                {
                    return "Muy Alto";
                }
                else if(numero<x)
                {    
                    return "Muy Bajo";
                }
                else if(numero==x)
                {
                    return "Adivinó";
                }
    
            } else
            {
                return "Ingrese un numero dentro del rango";
            }    
    
        }
    }
    

    和第二个jsp页面:

    <%@page import="java.text.*"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    <html>
        <head>
            <title>Adivinar</title>
        </head>
        <body>
            <h3>Bienvenido</h3>
            ${numero}
            <table>   
    
                <tr>
                    <td bgcolor='#CCCCCC'>
                        ${resultado}
                    </td>
                </tr>
    
            </table>
            <a href="adivina.html">Regresar</a>
        </body>
    </html>
    

    【讨论】:

    • 我在某处得到一个空字符串,我认为在 controlador.java 部分
    • 我不明白你为什么使用 Stateless 用一个简单的 java 类来实现它并在 servlet 中实例化它
    猜你喜欢
    • 2012-05-16
    • 2015-07-24
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多