- Dynamic Web Project 생성
- Java resource에 /test servlet 생성
- doGet( ) 메서드 로직 작성
- deploy
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 입력
// 2. 로직
// 3. 출력
// 결과를 client에게 돌려주기 위해서는
// 1. contentType을 설정
response.setContentType("text/html; charset=UTF-8");
// 2. stream을 열어서 내보내주기
PrintWriter out = new PrintWriter(response.getOutputStream());
out.println("소리없는 아우성!");
out.close();
}
- response에 포함된 결과 HTML을 Java Program 내에서 기술해야 한다.
- 이를 보완하기 위해 JSP가 등장한다.
JSP는 HTML과 유사하게 생겼다. ( 확장자.JSP )
가정 > 첫번째 호출
Servlet Container은 아무것도 없고, 우리가 만든 file 하나만 들고 있는 상태
- request가 오면 container는 hello.jsp를 hello_ jsp.java(servlet file)로 바꾼다.
- 내부적으로 hellojsp.java를 complie하고, hello jsp.class file이 생성된다.
- 해당 class에서 hello_jsp 인스턴스 객체가 만들어진다.
( 만들어진 instance = servlet )- container는 thread를 가지고, hello_jsp 인스턴스가 가지고 있는 메서드( _jsp Service( ) )를 호출한다.
- GET, POST 구분 X 무조건 _jsp Service( ) 메서드 호출됨
- hello_jsp는 _jsp Service( ) 메서드를 들고 있다.
( doGet( ), doPost( ) 메서드는 X )
JSP = Servlet
- 위의 방법과 같이 Translation된 것이 직접 구현한 것보다 성능이 더 좋다.
- JSP를 사용하는 것이 구현도 쉽고 성능도 좋기 때문에
- servlet이 사장되고, JSP가 사용되기 시작되었다.
- 주석 <%-- 주석 --%>
- directive <%@ 지시어 %>
- servlet class의 import 구문으로 들어감
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.ArrayList"%>
- declaration <%! 변수, method %>
- servlet class의 field와 method에 들어감
( 다른 client와 공유됨 )- scriptlet <% 코드(JAVA) %>
- _ jsp service( ) 메서드 내로 그대로 로직이 들어감
<% // 1. 입력받고 // 2. 로직처리 // 3. DB처리 request.setCharacterEncoding("UTF-8"); String name = request.getParameter("userName"); out.println("안녕하세요!"); %>
- Expression <%= 식 %>
- out.println의 인자로 들어감
이것은 소리없는 아우성!!!<br><br> 받은 데이터는 : <%= name %>
🚨주의🚨
HTML에서 상대경로를 지정할 때, /hello가 나오게 되는 경우, 기존 http://localhost:8080까지 잡히게 된다. 따라서 상대경로는 /html/hello.jsp로 주소를 잡는게 좋다!
JSP 코드내에서 그냥 사용할 수 있는 객체
- request 객체 → HttpServletRequest class type의 객체
- response 객체 → HttpServletResponse class type의 객체
- out 객체 → PrintWriter 객체
- session 객체 → HttpSession class 객체 → web client 당 1개씩 할당
client의 작업을 지속적으로 tracking 할 수 있음- application → ServletContext 객체 → 모든 servlet에 의해 공유되는 객체
- page → this와 비슷한 의미
Presentation Layer
Business Layer
Persistence Layer
Database LayerMVC pattern🚩
위 architecture를 적용해야 하기 때문에 JSP의 역할이 줄어들게 된다.
JSP를 이용한 출력은 하지 않고, 이를 Front-end단에서 맡게된다.
이로인해 JSP의 위상은 줄어들고 있다.