简体   繁体   English

servlet到JSP的变量以及JSP到servlet的变量

[英]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. 我有一个家庭作业,这是使用jsp和servlet创建剪刀石头布的基本练习。 On the index.html, I created a form to receive "Rock", "Paper" or "Scissors". 在index.html上,我创建了一个表单来接收“ Rock”,“ Paper”或“ Scissors”。 This goes into a Servlet which counts turns, defeats, wins, and ties. 这进入了一个Servlet,它计算转弯,失败,获胜和平局。

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. 提交动作(无论是石头,剪刀还是剪刀)后,您将被定向到一个JSP,该JSP将显示记分板和服务器的动作,但是在此JSP上有一种形式,一个是返回index.html和转,赢,失败计数器继续计数,然后有一个按钮,它是一个重置按钮,该按钮应将所有值都变为0,这是jsp上的不同形式,具有不同的动作。 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. 我的老师建议制作两个servlet,但是说如果可以用一个servlet可以,但是制作两个servlet会更容易。

Summary: How can I reset the variables on one servlet from another one? 简介:如何在一个servlet上从另一个servlet重置变量?

index.html: 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: 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 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: 第一个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: 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中,只需将它们声明为public,然后使用如下代码修改即可

 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 : 但这不是维护Servlet状态的正确方法,如果您在多个请求之间声明状态,则应使用以下代码将它们保存到会话中:

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

You can reset your variable in the doGet method of your servlet before you back to index.html page. 您可以在返回index.html页面之前,在servlet的doGet方法中重置变量。 Servlet attributes is good choice in your case. Servlet属性是您的最佳选择。 Servlet attributes defines three scope such as application Scope, session Scope, request Scope. Servlet属性定义了三个范围,例如应用程序范围,会话范围,请求范围。 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): 应用程序范围(自从启动Web应用程序以来,应用程序范围开始,而自关闭后,该应用程序范围结束):

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

Session scope (session scope starts when a client establishes connection with web application till client browser is closed): 会话范围(会话范围在客户端与Web应用程序建立连接,直到客户端浏览器关闭时开始):

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

You can refer to the post Servlet Request Session Application Scope Attributes to see more detail about Servlet attributes. 您可以参考Servlet请求会话应用程序范围属性一文,以了解有关Servlet属性的更多详细信息。

Hope this help! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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