학교/JAVA

모바일 웹 서비스를 위한 JSP 웹 프로그래밍 연습문제_05장 서블릿

서윤-정 2023. 12. 13. 20:12

01. GET 방식의 HTTP 요청을 처리하기 위한 서블릿의 멤버 함수 이름은 무엇인가요?

답: doGet

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // GET 요청 처리 로직 작성
}

 

 

02. 쿼리 스트링에서 이름이 name인 파라미터의 값을 추출하기 위한 HttpServletRequest 클래스의 멤버 함수 이름은 무엇인가요?

답: requset.getParameter();

String parameterValue = request.getParameter("name");

 

 

03. 체크 박스 형태의 HTML 페이지로부터 전달되는 입력 값을 추출하기 위해 가장 적절하게 이용할 수 있는 HttpServletRequest 클래스의 멤버 함수 이름은 무엇인가요?

답: request.getParameterValues();

 

 

 

04. 다음은 사용자로부터 좋아하는 색깔을 입력 받기 위한 color.html 이다. 다음 코드를 실행시켰을 때, 사용자가 입력한 값이 'Green'이라면, 'Favorite Color: Green'이 출력되도록 ColorServlet 코드를 작성해 주세요.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="Color">
		<input type="text" name="select" placeholder="Red or Green or Blue" checked>
		<input type="submit" value="입력">
	</form>
</body>
</html>

 

답:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String usel = request.getParameter("select");
		String res = "<html><h3>";
		res += "Favorite Color: ";
		res += usel;
		res += "</h3></html>";
		
		PrintWriter writer = response.getWriter();
		writer.print(res);
	}

 

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("/Color")
public class ColorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 사용자가 입력한 값 가져오기
        String favoriteColor = request.getParameter("select");

        // HTML로 응답 생성
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("Favorite Color: " + favoriteColor);
        response.getWriter().println("</body></html>");
    }
}

 

 

 

 

 

05. 다음 코드 city.html에서 [OK] 버튼을 눌렀을 때 선택된 값이 모두 출력될 수 있도록 CityServlet 코드를 작성해 주세요.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="Signup">
		<input type="checkbox" name="city" value="seoul" checked>서울<br>
		<input type="checkbox" name="city" value="busan" checked>부산<br>
		<input type="checkbox" name="city" value="incheon" checked>인천<br>
		<input type="submit" value="입력">
	</form>
</body>
</html>

 

답:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8"); // 한글 깨짐 방지
		
		String[] usel = request.getParameterValues("city");
		String res = "<html><h3>";
		try {
			for(int i=0; i<usel.length; i++) {
				res += usel[i] + " ";
			}
		} catch(NullPointerException e) {
			res += "잘못 된 입력값 입니다.";
		} finally {
			res += "</h3></html>";
			PrintWriter writer = response.getWriter();
			writer.print(res);
		}
	}

 

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 선택된 도시 값 가져오기
        String[] selectedCities = request.getParameterValues("city");

        // HTML로 응답 생성
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body>");
        writer.println("<h3>Selected Cities:</h3>");
        if (selectedCities != null) {
        	// selectedCities 배열을 순회. city 변수에는 각 반복에서 현재 도시명이 할당
            for (String city : selectedCities) {
                writer.println("<p>" + city + "</p>");
            }
        } else {
            writer.println("<p>No city selected.</p>");
        }
        writer.println("</body></html>");
    }

 

 

 

 

 

06. 아이디, 패스워드, 닉네임을 입력받는 signup.html 을 생성하고, 다음과 같이 실행 결과가 나오도록 SignupServlet을 작성해 주세요.

User ID : Kim 

Password: 111 

Name: Simin

 

답:

signup.html 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Signup Form</title>
</head>
<body>
    <form action="SignupServlet" method="post">
        User ID: <input type="text" name="userId"><br>
        Password: <input type="password" name="password"><br>
        Name: <input type="text" name="nickname"><br>
        <input type="submit" value="Signup">
    </form>
</body>
</html>

 

SignupServlet

import java.io.IOException;
import java.io.PrintWriter;
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("/SignupServlet")
public class SignupServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 입력값 가져오기
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");

        // HTML로 응답 생성
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body>");
        writer.println("<h3>Signup Information:</h3>");
        writer.println("<p>User ID: " + userId + "</p>");
        writer.println("<p>Password: " + password + "</p>");
        writer.println("<p>Name: " + nickname + "</p>");
        writer.println("</body></html>");
    }
}

 

 

 

 

 

07. 다음 sport.html을 실행하면 어떤 URL이 생성되나요?

(단, sport.html은 Hello 프로젝트에 포함되어 있다고 가정합니다.)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="Sport">
		<select name="sport" multiple="multiple">
			<option value="baseball">Baseball
			<option value="football" selected>Football
			<option value="volleyball" selected>Volleyball
		</select>
		<input type="submit" value="입력">
	</form>
</body>
</html>

 

답:

http://localhost:8080/Hello/Sport

localhost:8080/Hello/SportServlet?sport=football&sport=valleyball

 

 

 

 

08. 07번 문제의 sport.html을 실행했을 때 다음과 같은 결과가 출력되도록 SportServlet 클래스를 구현해 주세요.

selected sport: football
selected sport: volleyball

 

답:

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8"); // 한글 깨짐 방지
		
		String[] usel = request.getParameterValues("sport");
		String res = "<html>";
		try {
			for(int i=0; i<usel.length; i++) {
				res += "<h3>Selected sport: " + usel[i] + "</h3>";
			}
		} catch(NullPointerException e) {
			res += "<h3>잘못 된 입력값 입니다.</h3>";
		} finally {
			res += "</html>";
		}
		res += "</html>";
		PrintWriter writer = response.getWriter();
		writer.print(res);
	}
import java.io.IOException;
import java.io.PrintWriter;
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("/Sport")
public class SportServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 선택된 스포츠 값 가져오기
        String[] selectedSports = request.getParameterValues("sport");

        // HTML로 응답 생성
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body>");
        writer.println("<h3>Selected Sports:</h3>");
        if (selectedSports != null) {
            for (String sport : selectedSports) {
                writer.println("<p>selected sport: " + sport + "</p>");
            }
        } else {
            writer.println("<p>No sport selected.</p>");
        }
        writer.println("</body></html>");
    }
}