find_number_mvc.html : 숫자입력폼
FindNumberServlet : 숫자입력, 컴퓨터 난수저장, 정답판정문자열, jsp에게 포워드
find_number_mvc.jsp : findNumberMvcServlet이 전달한 문자열 출력
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>숫자 맞추기 게임 MVC</h1>
<form action ="findNumberServlet">
<fieldset>
<legend>숫자입력</legend>
숫자(1~100) : <input type="number" name="num">
<input type= "submit" value="정답확인">
</fieldset>
</form>
</body>
</html>
package web0816.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/findNumberServlet")
public class FindNumberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
int com_num = new java.util.Random().nextInt(100)+1;
public FindNumberServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num = request.getParameter("num");
int i = Integer.parseInt(num);
String result="";
if( com_num==i) {
result= "추카추카,정답입니다.";
}else if(com_num<i) {
result= "숫자를 낮춰주세요";
}else {
result="숫자를 올려주세요";
}
request.setAttribute("result", result);
request.getRequestDispatcher("/find_number_mvc.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String result = (String)request.getAttribute("result"); //다운캐스팅 필수
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> find_number_mvc.jsp</h1>
결과 :<%=result %>
</body>
</html>