숫자맞추기 게임 MVC패턴

채종윤·2023년 8월 16일
0

1. 숫자맞추기 게임을 MVC패턴으로 작성하세요

1) html(입력폼) -> 서블릿 (입력처리,로직) -> 포워드 -> jsp(출력)

find_number_mvc.html : 숫자입력폼
FindNumberServlet : 숫자입력, 컴퓨터 난수저장, 정답판정문자열, jsp에게 포워드
find_number_mvc.jsp : findNumberMvcServlet이 전달한 문자열 출력

2.find_number_mvc.html (입력)

<!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>

3.FindNumberSerlvet (로직)

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

}
                            

4.find_number.mvc.jsp (출력)

<%@ 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>
profile
안녕하세요. 백앤드 개발자를 목표로 하고 있습니다!

0개의 댓글