19.05.23 고급 서블릿 활용 (model 2 7강)

Back-End/JSP 2019. 5. 23. 10:27
728x90
반응형

-예제 및 출력 결과-


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package control;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld"// /HelloWorld라고 주소 url에 표시해주어야 이 서블릿 클래스가 실행됩니다.
                            // 만약 코드를 (" ") 안쪽에 주소를 변경하면 실행되지 않는다. (인위적으로 변경시 실행가능)
                            // 이것을 url 매핑이라 한다. (url과 서블릿이 동일해야 실행된다.)
 
public class HelloWorld extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        reqPro(request, response);
    }
 
    // Get방식과 Post방식을 둘다 처리해주는 메소드를 만들면 편하다.
    // 일괄처리 즉, doget 이던 dopost 이던 아래 reqpro 메소드가 실행되게 해줌
    protected void reqPro(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        // 화면에 Helloworld 라고 출력을 하고 싶어요.. jsp 쪽으로 넘겨질 데이터를 설정
        String msg = "Hello World~~ 안녕하세요.";
        Integer data = 12;
 
        // jsp 쪽으로 데이터를 request에 부착하여 넘겨줌
        // setAttribute는 오브젝트 타입이므로 모든 객체를 다 집어넣을 수 있다.
        request.setAttribute("msg", msg);
        request.setAttribute("data", data);
 
        // 서블릿에서 jsp를 호출하면서 데이터를 같이 넘겨주는 객체 RequestDispatcher(인터페이스) 를 선언
        RequestDispatcher rd = request.getRequestDispatcher("HelloWorld.jsp"); // jsp 파일명을 기술
        // jsp로 (request, response) 데이터를 이동
        rd.forward(request, response);
 
    }
 
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
 
    <center>
        <h2>결과 보기</h2>
 
        인사말 : ${msg }
        <p>숫자 : ${data }
    </center>
</body>
</html>
 
cs


HelloWorld URL과 매핑된 값이 출력된다.



728x90
반응형
: