#Spring - 4.Integrating Servlets and JSP
본문 바로가기
Programming/Spring

#Spring - 4.Integrating Servlets and JSP

by 권가 2019. 6. 11.

1. MVC Architecture

모델, 뷰 및 컨트롤러를 구분하는 디자인 패턴이다.
- Model(Java Beans)
    응용 프로그램의 상태를 나타낸다.
- View(JSP)
    디스플레이 데이터 또는 프리젠테이션 담당한다.
- Controller(Servlet)
    뷰와 모델 사이의 인터페이스 역할.

 

    비즈니스 로직 처리를 위해 사용자로부터 요청을 받고 백엔드 서비스를 호출하는 것을 책임진다.

    처리 후 백엔드 서비스는 일부 데이터를 반환하여 보기를 표시할 수 있다.
    컨트롤러가 이 데이터를 수집하고, 표시할 뷰에 대한 모델을 준비한다.

MVC Architecture

1. 브라우저는 Servlet에 요청을 보낸다.
2. Servlet은 요청 결과를 담은 Java Bean을 인스턴스화한다.
3. Servlet은 JSP 페이지와 통신한다.
4. JSP 페이지는 Java Bean과 통신한다.
5. JSP 페이지는 브라우저에 응답한다.

 

MVC Flow of Control

2. Implementing MVC with RequestDispatcher

1. 결과 데이터를 나타낼 bean 정의
getXXX 메서드가 하나 이상인 일반 Java 클래스

2. Servlet을 사용하여 요청 처리
Servlet은 요청 매개변수 읽기, 누락 및 잘못된 형식의 데이터 확인, 호출 비즈니스 논리 등

3. 사업논리를 수행하여 결과가 담긴 bean을 구한다.
Servlet은 비즈니스 논리(애플리케이션별 코드) 또는 데이터 액세스 코드를 호출하여 결과를 얻는다.

4. 요청, 세션 또는 Servlet 컨텍스트에 bean 저장
Servlet은 요청, 세션 또는 Servlet 컨텍스트 객체에 setAtribe를 호출하여 요청 결과를 나타내는 bean에 대한 참조를 저장한다.

 

5. JSP 페이지로 요청 전달
Servlet은 상황에 적합한 JSP 페이지를 결정하고 RequestDispatcher의 전달 방법을 사용하여 해당 페이지로 제어 권한을 전송한다.

6. Bean에서 데이터를 추출한다.
- JSP 1.2(옛날 것!)
    JSP 페이지는 jsp:useBean과 4단계의 위치와 일치하는 scope로 Bean에 접근한다. 그런 다음 페이지에서는                  jsp:getProperty를 사용하여 Bean 속성을 출력한다.
- JSP 2.0(기본 설정!) : 표현 언어
    JSP 페이지에서 ${nameFromServlet.property}를 사용하여 Bean 속성 출력

- 어느 쪽이든 JSP 페이지는 Bean을 만들거나 수정하지 않고, 단지 Servlet이 만든 데이터를 추출하여 표시할 뿐이다.

 

Java Bean as a Model

public class Customer {

    private String id;
    private String name;
    private String email;

    public Customer(String id, String name, String email) {
	this.id = id;
	this.name = name;
	this.email = email;
    }

    // getter, setter
    // …
}

Servlet as a Controller

protected void doGet(HttpServletRequest request,
			HttpServletResponse response) 
	throws ServletException, IOException {

	// servlet reads request parameters
	String customerId = request.getParameter("customerId");

	// Do business logic and get a bean that contains result
	// ...
	
 	// Store the bean in the request context
    	request.setAttribute("customer", customer);
    
	// forward the request to a jsp page
    String address;
    if (customer == null) {
      request.setAttribute("badId", customerId);
      address = "/error.jsp";
    } else  {
      address = "/success.jsp";
    } 

	RequestDispatcher dispatcher =
      	request.getRequestDispatcher(address);
    dispatcher.forward(request, response);
}

JSP as a View

<%-- JSP 1.2(old) --%>
<jsp:useBean id="customer" type="beans.Customer" scope="request"> 
</jsp:useBean>

<ul>
  <li>Name: <jsp:getProperty name="customer" property="name" /></li>
  <li>Email: <jsp:getProperty name="customer" property="email" /></li>  
  <li>ID: <jsp:getProperty name="customer" property="id" /></li>
 </ul>
<%-- JSP 2.0(Preferred)  --%>
<ul>
  <li>Name: ${customer.name}</li>
  <li>Email: ${customer.email}</li>  
  <li>ID: ${customer.id}</li>
 </ul> 

 

JSP EL(expression language)

JSP 2.0의 주요 구성 요소 중 하나는 EL이라는 새로운 표현 언어이다.
표현식 언어를 사용하면 JavaBeans 구성 요소에 저장된 애플리케이션 데이터에 쉽게 액세스할 수 있다.

형식: 단순 변수에 대한 ${name} 
속성에 대한 ${name.bar}

3. Scopes

'Scopes'는 Bean이 저장되어 있는 곳이다. Bean이 보이는 장소와 시간을 조절한다.

세 가지 선택
- Request
요청에 저장된 데이터는 ServletServlet이 앞으로 전달되는 페이지에 표시된다. 데이터는 다른 사용자나 다른 페이지에서 볼 수 없다. 가장 일반적인 범위.
- Session *보통
요청에 저장된 데이터는 ServletServlet이 앞으로 전달되는 페이지에 표시된다. 데이터는 동일한 사용자일 경우 다른 페이지 또는 나중에 볼 수 있다. 데이터는 다른 사용자가 볼 수 없다.
- Application(Servlet Context) *거의 안씀
Servlet 컨텍스트에 저장된 데이터는 애플리케이션의 모든 사용자와 모든 페이지가 볼 수 있다.

 

Request-based 데이터 공유

Servlet

Customer myCustomer = Lookup.findCustomer(request.getParameter("customerID"));
request.setAttribute("customer", myCustomer);

RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);

JSP 2.0

${customer.firstName}}

JSP 1.2

<jsp:useBean id="customer" type="somePackage.Customer“ scope="request" />
<jsp:getProperty name="customer" property="firstName"/>

4. Beans

특정 규칙을 따르는 Java 클래스
- 0 인수(빈) 구성자가 있어야 함
    이러한 생성자를 명시적으로 정의하거나 모든 생성자를 생략하여 이 요구 사항을 충족할 수 있음
- 공개 인스턴스 변수(필드)가 없어야 함
- 지속적인 값은 getXxx 및 setXxx라는 방법을 통해 접근해야 함

Bean 예:

package coreservlets;

public class StringBean {

    private String message = "No message specified";

    public String getMessage() {
        return(message);
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Beans 접근하기

JSP Expression Language

${customer.firstName}}

JSP Action Tag

<jsp:useBean id="customer" type="somePackage.Customer" scope="request" />
<jsp:getProperty name="customer" property="firstName"/>

 

정리.

MVC 접근법
- Servlet이 원래 요청에 응답함
- Servlet은 비즈니스 논리에 대해 설명하고 결과를 Bean에 저장한다.
    HttpServletRequest, HttpSession 또는 ServletContext에 저장된 Bean
- Servlet은 RequestDispatcher.forward를 통해 JSP 페이지를 호출함
- JSP 페이지는 Bean에서 데이터를 읽는다.
최신 서버: ${beanName.propertyName}
JSP 1.2 서버: 적절한 범위(요청, 세션 또는 애플리케이션)와 jsp:getProperty를 갖춘 jsp:useBean

 

+JSTL

JSP With JSTL(JSP Standard Tag Library)

(끝난줄 알았는데 더 있다고 눈 찌푸리면 안돼요!)

 

1. What is JSTL?

많은 JSP 응용프로그램에 공통적으로 사용되는 핵심 기능을 캡슐화하는 유용한 JSP 태그 모음이다.
JSTL은 JSP 프로그래머가 Java 코드(JSP 스크립트릿)가 아닌 태그를 사용하여 프로그래밍할 수 있도록 하기 위해 도입되었다.

 

2.Using JSTL

Maven Dependency

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Declare JSTL

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

3. JSP Scriptlet vs JSTL

- JSP Scriptlet(java와 혼용)

<html>
<head>
<title>Count to 10 in JSP scriptlet</title>
</head>
<body>
   <%
      for(int i=1;i<=10;i++){
   %>
   <%=i%><br />
   <%
      }
   %>
</body>
</html>

- JSTL(태그로 모두 구성)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Count to 10 Example (using JSTL)</title>
</head>
<body>
   <c:forEach var="i" begin="1" end="10" step="1">
      <c:out value="${i}" />
      <br />
   </c:forEach>
</body>
</html>

4. JSTL tag library groups

- core

- Formatting tags

- SQL tags

- XML tags

- JSTL Functions

http://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm참고하세요~

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<title>If with Body</title>
</head>

<body>
   <c:if test="${pageContext.request.method=='POST'}">
      <c:if test="${param.guess=='Java'}">You guessed it!
      </c:if>

      <c:if test="${param.guess!='Java'}">You are wrong
      </c:if>
   </c:if> <br/>

   <form method="post">
      Guess what computer language I am thinking of? 
      <input type="text“ name="guess" /> 
      <input type="submit" value="Try!" /> 
    </form>
</body>
</html>

댓글