vendredi 10 juin 2016

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?


I am making a guess the number application using a servlet, when i enter a number and press the "guess button" it sends me to a jsp page and tells me if the number is too low, too high or if i guessed it correctly. I have a link in my jsp page that take me back to the html page to guess again.

My question is that, how do i keep my generated number that i need to guess when going back an forth from the html page to my jsp page so i can keep guessing that same number?? For example if the number i need to guess is 50 and i press the "guess button" and it takes to me to the jsp, no matter what the result is, how do i keep that number until i close the web page? (NOTE: when i use <%= session.getAttribute("numero") %> i get NULL )

This my code:

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);
    }

}

This is my 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>

This is my 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>

This is my number generating class:

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;
    }
}

Aucun commentaire:

Enregistrer un commentaire