← Back to quizzesFree quiz

JSP 프로그래밍 기본 개념

JavaServer Pages (JSP) is a server‑side technology that enables developers to embed Java code directly into HTML. This course explains the core concepts tested in the quiz, from the JSP…

10 questions~5 min
JSP 프로그래밍 기본 개념 — Qwi
0 / 10
Score: 0%
1

JSP 페이지가 브라우저에 전달되는 최종 HTML은 언제 생성되나요?

2

다음 JSP 코드에서 <%= base %> 가 출력하는 값은 무엇인가요? <% int base = 12000; %> 단가 원: <%= base %>

3

if 문에서 조건이 true이면 total 에서 5000을 차감하도록 하는 올바른 코드는?

4

배열 names 에 저장된 상품 중 재고가 0이 아닌 경우만 출력하려면 어떤 조건을 사용해야 하나요?

5

다음 코드에서 avg 변수에 소수점 결과를 얻기 위해 필요한 수정은?

6

주문 금액이 400,000원 이상이면 5% 할인을 적용하는 조건식은?

7

다음 중 JSP 페이지에 선언된 변수는 서버에서만 존재하고 클라이언트에 노출되지 않는다. 어느 설명이 맞나요?

8

다음 JSP 코드에서 total 변수의 초기값은 얼마인가요? <% int base = 12000; int count = 4; int total = base * count; %>

9

JSP 페이지에서 컴파일 오류와 논리 오류를 구분할 때 올바른 설명은?

10

다음 조건식에서 && 와 || 의 차이를 설명할 때 옳은 것은?

Understanding JSP Programming Basics

JavaServer Pages (JSP) is a server‑side technology that enables developers to embed Java code directly into HTML. This course explains the core concepts tested in the quiz, from the JSP lifecycle to common programming patterns such as conditional statements, array handling, and type conversion. By the end of this module you will be able to write, debug, and optimize JSP pages with confidence.

1. JSP Lifecycle – When Is the Final HTML Generated?

When a client (browser) requests a .jsp file, the following steps occur on the server:

  • Translation: The JSP file is translated into a Java servlet source file.
  • Compilation: The generated servlet source is compiled into a .class file.
  • Initialization: The servlet container creates an instance of the servlet and calls its init() method.
  • Execution: For each request, the container invokes the servlet’s service() method, which runs the embedded Java code.
  • Response: The servlet writes the resulting HTML (or other markup) to the response output stream, which the browser finally receives.

The final HTML is therefore produced when the server compiles and executes the JSP, not when the client merely requests the file. Understanding this flow is essential for debugging performance issues and for correctly placing dynamic content.

2. Scriptlets and Expressions – Displaying Variables

JSP provides three main ways to embed Java code:

  • <% ... %> – scriptlet: arbitrary Java statements executed on the server.
  • <%= ... %> – expression: evaluates an expression and inserts its toString() result into the HTML output.
  • <%! ... %> – declaration: defines class‑level members (fields or methods) that become part of the generated servlet.

Consider the following snippet:

<% int base = 12000; %>
<p>Unit price: <%= base %></p>

The scriptlet creates a local variable base. The expression <%= base %> evaluates that variable and writes 12000 into the HTML response. If the expression were omitted, the variable would remain invisible to the client.

3. Conditional Logic – Using if Statements

Conditional statements control the flow of execution. In JSP, you typically write them inside scriptlets. The quiz asked for a condition that subtracts 5,000 from total only when the condition is true. The correct form is:

<% if (total >= 40000) { total -= 5000; } %>

Key points to remember:

  • Use >= when the requirement is "greater than or equal to".
  • The body of the if block can contain any valid Java statements, including further calculations or output.
  • Always close the scriptlet with %> to avoid syntax errors.

4. Working with Arrays – Filtering Non‑Zero Stock Items

Suppose you have two parallel arrays: String[] names and int[] stocks. To display only products that are in stock, you need a condition that checks the stock value:

<% for (int i = 0; i < names.length; i++) { %>
  <% if (stocks[i] != 0) { %>
    <p><%= names[i] %> – Stock: <%= stocks[i] %></p>
  <% } %>
<% } %>

The expression stocks[i] != 0 ensures that only items with a positive inventory are rendered. Using == 0 would produce the opposite effect, while checking prices[i] > 0 would be unrelated to stock availability.

5. Numeric Type Conversion – Getting Decimal Results

Java performs integer division when both operands are of type int. To retain the fractional part, at least one operand must be a floating‑point type. The quiz highlighted the correct conversion:

double avg = (double) price / count;

Explanation:

  • price is cast to double, promoting the whole expression to floating‑point arithmetic.
  • The result is stored in a double variable, preserving any decimal digits.
  • Alternative casts such as price / (double) count also work, but the chosen form matches the quiz answer.

6. Business Rules – Applying a Discount

When the total order amount reaches a threshold, a discount is applied. The correct conditional statement is:

<% if (total >= 400000) { discount = (int)(total * 0.05); } %>

Important considerations:

  • The comparison uses >= because the rule applies to "400,000원 이상" (greater than or equal to).
  • The multiplication by 0.05 yields a double; casting to int truncates any fractional won, which is typical in Korean currency calculations.
  • Using <= or == would either give the wrong range or limit the discount to a single exact value.

7. Scope of Scriptlet Variables – Server‑Side Visibility Only

Variables declared inside a scriptlet (<% ... %>) exist only on the server during the request processing. They are never sent to the client as part of the HTML output unless explicitly written to the response. This encapsulation provides:

  • Security – Sensitive data (e.g., database credentials) stays hidden.
  • Performance – No unnecessary data is transmitted.
  • Maintainability – Business logic remains separate from presentation markup.

For example:

<% String secret = "admin123"; %>
<!-- The variable 'secret' is not visible in the generated HTML -->
<p>Welcome, user!</p>

8. Calculating Totals – Initializing Variables

In JSP you can perform arithmetic directly inside a scriptlet. The following code calculates the total price for four items each costing 12,000원:

<% int base = 12000; int count = 4; int total = base * count; %>

The result stored in total is 48,000. This demonstrates how simple Java expressions can be used to build dynamic content without needing external libraries.

9. Best Practices for Writing Clean JSP

  • Separate concerns: Keep business logic in Java classes (servlets, beans) and use JSP mainly for view rendering.
  • Avoid scriptlets when possible: Modern JSP encourages JSTL and EL (Expression Language) to reduce Java code in pages.
  • Use proper encoding: Declare page encoding with <%@ page contentType="text/html; charset=UTF-8" %> to support Korean characters.
  • Validate user input: Always sanitize request parameters before using them in calculations.
  • Cache compiled JSP: Most servlet containers automatically cache the generated servlet, improving response time for subsequent requests.

10. Quick Review – Key Takeaways

  • The final HTML is generated when the server compiles and executes the JSP.
  • Scriptlet variables are server‑side only; expressions output their values to the client.
  • Use if (condition) { ... } with the correct relational operator for business rules.
  • Check array elements with != 0 to filter out zero‑stock items.
  • Cast integers to double before division to retain decimal places.
  • Apply discounts with >= and cast the result to int when dealing with currency.
  • Initialize variables correctly; arithmetic in scriptlets follows standard Java rules.

By mastering these fundamentals, you will be equipped to develop robust JSP pages that efficiently generate dynamic HTML, enforce business logic, and maintain clean separation between server‑side processing and client‑side presentation.