简体   繁体   中英

Variables on servlet to JSP and JSP to servlet

I have a homework which is a basic exercise of creating rock paper scissors with jsp and servlets. On the index.html, I created a form to receive "Rock", "Paper" or "Scissors". This goes into a Servlet which counts turns, defeats, wins, and ties.

Once you submit your move be it rock, paper or scissor, you will be directed to a JSP that will show a scoreboard and the server's move but on this JSP there's a form, one is a link to go back to the index.html and the turn, wins, defeats counter keeps on counting and then there's a button which is a reset button that should turn all values into 0, this is a different form on the jsp with a different action. My teacher suggested making two servlets but said that if I can make it with one it would be ok but that making two servlets would be easier.

Summary: How can I reset the variables on one servlet from another one?

index.html:

<html>
<head>
    <title>Actividad 4</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1>Rock Paper Scissors Game</h1>
    <p>Choose your attack: </p>
    <form method="post" action="move.do">
        <select name="attack">
            <option value="1">Rock</option>
            <option value="2">Scissors</option>
            <option value="3">Paper</option>
        </select>
        <button type="submit">Attack!</button>
    </form>
</body>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> 30 Servlet Act 4 Servlet Servlet Act 4 /move.do

<servlet>
    <servlet-name>Servlet2 Act 4</servlet-name>
    <servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet2 Act 4</servlet-name>
    <url-pattern>/reset.do</url-pattern>
    <init-param>
        <param-name>turn</param-name>
        <param-value>1</param-value>
    </init-param>
</servlet-mapping>

First servlet:

import java.io.IOException;

import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.RequestDispatcher;
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 maple
 */
@WebServlet(name = "Servlet Act 4", urlPatterns = {"/Servlet"})
public class Servlet extends HttpServlet {
    static int turn = 1;
    static int wins = 0;
    static int defeat = 0;
    static int ties = 0;

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Servlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet Servlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int attack = Integer.parseInt(request.getParameter("attack"));
    int move = randMove();
    String counter = "";
    String decision = "";
    //Checa el metodo randMove(), obtengo un numero aleatorio entre 1 a 3 que lo convierto en
    //Rock = Piedra
    //Scissor = Tijera
    //Paper = Papel
    switch(move) {
        case 1: counter = "Rock";
        break;
        case 2: counter = "Scissor";
        break;
        case 3: counter = "Paper";
        break;
    }

    //Este if comparo que si los dos son iguales, el piedra papel o tijera del servidor
    //Y el piedra papel tijera del jugador para determinar el ganador.
    if(attack == move) {
        ties++;
        decision = "It's a tie!";
    } else if (attack == 1) {
        switch(move){
            case 2: decision = "Player wins!";
            wins++;
            break;
            case 3: decision = "Server wins!";
            defeat++;
            break;
        }
    } else if (attack == 2) {
        switch(move){
            case 1: decision = "Server wins!";
            defeat++;
            break;
            case 3: decision = "Player wins!";
            wins++;
            break;
        }
    } else if (attack == 3) {
        switch(move) {
            case 1: decision = "Player wins!";
            wins++;
            break;
            case 2: decision = "Server wins!";
            defeat++;
            break;
        }
    }

    //Esto es para mantener cuenta que turno es, que movimiento hizo, quien gano, cuantas veces
    //gano quien y perdio quien.
    request.setAttribute("turn", turn);
    request.setAttribute("counter", counter);
    request.setAttribute("winner", decision);
    request.setAttribute("ties", ties);
    request.setAttribute("wins", wins);
    request.setAttribute("defeat", defeat);
    if(turn < 5) {
        turn++;
    } else {
        turn = 1;
        ties = 0;
        wins = 0;
        defeat = 0;
    }
    RequestDispatcher view = 
            request.getRequestDispatcher("Scoreboard.jsp");
    view.forward(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

public static int randMove() {
    int min = 1;
    int max = 3;
    Random rand = new Random();
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

}

The JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Scoreboard</title>
    </head>
    <body>
        <h1>Server: <%=request.getAttribute("counter")%></h1>
        <h3>Round <%=request.getAttribute("turn")%> of 5</h3>
        <p><%=request.getAttribute("winner")%></p>
        <table>
            <thead>
                <tr>
                    <td></td>
                    <td>Win</td>
                    <td>Defeat</td>
                    <td>Tie</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Player</td>
                    <td><%=request.getAttribute("wins")%></td>
                    <td><%=request.getAttribute("defeat")%></td>
                    <td><%=request.getAttribute("ties")%></td>
                </tr>
                <tr>
                    <td>Server</td>
                    <td><%=request.getAttribute("defeat")%></td>
                    <td><%=request.getAttribute("wins")%></td>
                    <td><%=request.getAttribute("ties")%></td>
                </tr>
            </tbody>
        </table>
        <form method="get" action="reset.do">
            <a type="button" href="index.html">Next round</button></a>
            <button type="submit">Reset</button>
        </form>
    </body>
</html>

The variable turn, wins, defeat and ties are all static, so if you want change then in another servlet, just declare them as public, then you and modify them with code like

 Servlet.turn = 0 

but this is not correct way to maintenance the state at servlet, if you state across requests, you should save them to session with code like :

request.getSession().setAttribute("turn",0);

You can reset your variable in the doGet method of your servlet before you back to index.html page. Servlet attributes is good choice in your case. Servlet attributes defines three scope such as application Scope, session Scope, request Scope. However, you can use application Scope, session Scope to resolve your issue like below:

Application scope (application scope starts since a web application is started and ends since it is shutdown):

request.getServletContext().setAttribute("turn", "0");

Session scope (session scope starts when a client establishes connection with web application till client browser is closed):

session.setAttribute("turn", "0");

You can refer to the post Servlet Request Session Application Scope Attributes to see more detail about Servlet attributes.

Hope this help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM