[英]Variables on servlet to JSP and JSP to servlet
我有一個家庭作業,這是使用jsp和servlet創建剪刀石頭布的基本練習。 在index.html上,我創建了一個表單來接收“ Rock”,“ Paper”或“ Scissors”。 這進入了一個Servlet,它計算轉彎,失敗,獲勝和平局。
提交動作(無論是石頭,剪刀還是剪刀)后,您將被定向到一個JSP,該JSP將顯示記分板和服務器的動作,但是在此JSP上有一種形式,一個是返回index.html和轉,贏,失敗計數器繼續計數,然后有一個按鈕,它是一個重置按鈕,該按鈕應將所有值都變為0,這是jsp上的不同形式,具有不同的動作。 我的老師建議制作兩個servlet,但是說如果可以用一個servlet可以,但是制作兩個servlet會更容易。
簡介:如何在一個servlet上從另一個servlet重置變量?
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>
第一個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;
}
}
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>
可變的轉彎,勝利,失敗和平局都是靜態的,因此,如果要更改,則在另一個servlet中,只需將它們聲明為public,然后使用如下代碼修改即可
Servlet.turn = 0
但這不是維護Servlet狀態的正確方法,如果您在多個請求之間聲明狀態,則應使用以下代碼將它們保存到會話中:
request.getSession().setAttribute("turn",0);
您可以在返回index.html頁面之前,在servlet的doGet方法中重置變量。 Servlet屬性是您的最佳選擇。 Servlet屬性定義了三個范圍,例如應用程序范圍,會話范圍,請求范圍。 但是,您可以使用應用程序范圍,會話范圍來解決您的問題,如下所示:
應用程序范圍(自從啟動Web應用程序以來,應用程序范圍開始,而自關閉后,該應用程序范圍結束):
request.getServletContext().setAttribute("turn", "0");
會話范圍(會話范圍在客戶端與Web應用程序建立連接,直到客戶端瀏覽器關閉時開始):
session.setAttribute("turn", "0");
您可以參考Servlet請求會話應用程序范圍屬性一文,以了解有關Servlet屬性的更多詳細信息。
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.