Notice
Recent Posts
Recent Comments
Link
05-03 02:05
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

<<개발일지>>

JSP - Java Server Page 본문

servlet, jsp

JSP - Java Server Page

개발하는지호 2024. 1. 28. 16:29

JSP, Java Server Page

JSP는 간단하게 Java code in HTML을 의미한다.

 

서블릿 기반 HTML 페이지 구현에서 봤듯이, Java 코드에 HTML을 문자열 형태로 작성하기엔 무리가 있다.

 

따라서, HTML 문서에 Java 코드를 작성하는 것이 더 편리할 것 같다는 취지에서 등장했다.

 

*Servlet 기반 구현과 기능은 동일

 

MVC 패턴의 등장

 

비즈니스 로직은 서블릿처럼 다른 곳에서 처리 JSP는 목적에 맞게 HTML 화면을 그리는 일에만 집중

 

Controller(컨트롤러) : HTTP 요청 받아서 파라미터 검증, 비즈니스 로직 수행

 

Model(모델) : 뷰에 출력할 데이터 보관, 뷰는 화면 렌더링에만 집중이 가능

 

View(뷰) : 모델에 담겨있는 데이터를 사용해서 화면을 그리는 일(HTML 생성)에 집중

 

 

 

JSP의 예시

1. 일반적인 HTML -> 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="index.html">HOME</a>
	<form action="practice-login" method="post">
		<div>
			<label for="id">아이디</label> <input type="text" name="id" id="id"
				placeholder="아이디를 입력하세요">
		</div>
		<div>
			<label for="password">비밀번호</label> <input type="password"
				name="password" id="password" placeholder="비밀번호를 입력하세요">
		</div>
		<div>
			<button type="submit">로그인</button>
		</div>
	</form>
</body>
</html>

이거를

 

JSP로 바꾸면 이렇게 된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>기존 커피 수정</h2>
    <form action="coffees/update" method="POST">
        <label for="coffee-id">수정할 커피 id:</label>
        <input type="text" id="coffee-id" name="coffeeId">
        <label for="coffee-name">커피 이름:</label>
        <input type="text" id="coffee-name" name="coffeeName">
        <p>커피 사이즈 </p>
          <input type="radio" id="tall" name="coffeeSize" value="TALL">
          <label for="tall">TALL</label><br>
          <input type="radio" id="grande" name="coffeeSize" value="GRANDE">
          <label for="grande">GRANDE</label><br>
          <input type="radio" id="venti" name="coffeeSize" value="VENTI">
          <label for="venti">VENTI</label>
        <br /><br />
        <label for="coffee-price">가격:</label>
        <input type="number" id="coffee-price" name="coffeePrice">
        <br /><br />
        <button type="submit">수정하기</button>
    </form>
</body>
</html>

 

이 역시 form action = "coffees/update" 인 WebServlet으로 가서 로직이 작동한다.

 

2. Servlet에게 forwarding으로 데이터를 받아 view 생성

 

서블릿

@WebServlet("/showCoffee")
public class CoffeeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 비즈니스 로직을 처리
        Coffee coffee = coffeeService.getCoffee();

        // JSP에 데이터 전달
        request.setAttribute("coffee", coffee);

        // JSP로 포워딩
        RequestDispatcher dispatcher = request.getRequestDispatcher("coffee.jsp");
        dispatcher.forward(request, response);
    }
}

 

forwarding 후 JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Coffee Page</title>
</head>
<body>
    <h2>Coffee Details</h2>
    <% 
        Coffee coffee = (Coffee) request.getAttribute("coffee");
        if (coffee != null) {
    %>
        <p>Name: <%= coffee.getName() %></p>
        <p>Price: <%= coffee.getPrice() %></p>
    <% 
        } else { 
    %>
        <p>Coffee not found.</p>
    <% 
        } 
    %>
</body>
</html>

 

 

*이렇게 함으로써 정적인 HTML를 만들 수 있는 동시에 동적인 HTML 구현이 가능해졌다.