index.jsp파일에서 HelloServlet.java(Servlet)로 데이터를 요청하면, 서블릿에서 다시 JSP로 데이터를 json형태로 보내주는 것을 구현해보자.

즉, web에서 jsp는 client 측이고, servlet은 server 측이다.

jsp에서는 버튼을 누르면, $.ajax() 메서드를 통해 servlet으로부터 데이터를 받게 되고,

servlet에서 여러가지 type의 데이터를 json 형태로 바꿔 보내주도록 한다.

 

0. jsp에서 servlet으로 데이터 전송하기

먼저, servlet에서 getParameter()를 이용해 jsp로부터 매개변수를 넘겨받을 준비를 한다.

 

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
package ajax3;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dto.Human;
import net.sf.json.JSONObject;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doGet()");
    
        String id = req.getParameter("id");
        String pw = req.getParameter("pw");
        
        System.out.println("id: " + id + " pw: " + pw); // 서버가 클라이언트로부터 데이터를 받은 상태
        
    }    
    
}
 
cs

jsp 파일(index.jsp)은 다음과 같다.

 

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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
//             data: "id=abc&pw=123",
            data:{id:"abc", pw:"123"}, // json 방식으로 서블릿에 보낼 데이터
            success:function(data){
                alert("success");
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

그 결과 다음과 같은 결과가 콘솔창에 나타난다.

이제 총 4가지의 타입의 객체를 서블릿에서 jsp로 보내주는 코드를 작성해본다.

위와 중복되는 부분은 제외하고 수정된 부분만 비교해보면

1. String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String str = "안녕하세요";
        
        JSONObject jObj = new JSONObject();
        jObj.put("str", str); // key, value
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
cs

 

 

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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"str":"안녕하세요"}
                alert(data.str); // 안녕하세요
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

2. Object(Human.java)

Human.java 는 다음과 같다.

 

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
package dto;
 
import java.io.Serializable;
 
public class Human implements Serializable{
    
    private String name;
    private int age;
    
    public Human() {
    }
 
    public Human(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    
}
 
cs

Human 객체를 참조하기 위한 변수 human을 servlet에서 생성하여 사용한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // Object
        
        // dto
        
        Human human = new Human("홍길동"24);
        
        JSONObject jObj = new JSONObject();
        jObj.put("human", human);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
cs

 

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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"human":{"age":24,"name":"홍길동"}}
                alert(data.human.name); // 홍길동
                alert(data.human.age); // 24
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

3. list

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // list
        
        List<Human> list = new ArrayList<Human>();
        list.add(new Human("홍길동"24));
        list.add(new Human("성춘향"16));
        list.add(new Human("홍두께"22));
        
        JSONObject jObj = new JSONObject();
        jObj.put("list", list);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
cs

 

 

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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"list":[{"age":24,"name":"홍길동"},{"age":16,"name":"성춘향"},{"age":22,"name":"홍두께"}]}
                alert(data.list[1].name); // 성춘향
                alert(data.list[0].age); // 24
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

4. HashMap

다양한 자료형의 값들을 넣어서 json 형태로 바꾼 후 jsp로 보내주도록 한다.

 

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
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // Map
        
        String str = "안녕하세요";
        
        List<Human> list = new ArrayList<Human>();
        list.add(new Human("홍길동"24));
        list.add(new Human("성춘향"16));
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", str);
        map.put("mylist", list);
        
        JSONObject jObj = new JSONObject();
        jObj.put("map", map);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
    }    
    
}
cs

 

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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"map":{"mylist":[{"age":24,"name":"홍길동"},{"age":16,"name":"성춘향"}],"title":"안녕하세요"}}
                alert(data.map.mylist[1].name); // 성춘향
                alert(data.map.title); // 안녕하세요
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Java > JSP, Servlet' 카테고리의 다른 글

JSP 내장 객체(out, request, session, pageContext)  (0) 2023.02.07
Servlet 정리  (0) 2023.02.06

간단하게 사용하는 코드를 저장하고, 자세한 설명은 다른 게시물에 추가하도록 하자.

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<%@ 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>
 
<%-- 
 
    내장 객체 : 동적으로 할당(생성)하지 않고 (언제든지 바로) 사용할 수 있는 객체
    
    out: web으로 출력
    request
    response
    session
    pageContext
    application
         :
--%>
 
<h3>out(web에 출력)</h3>
 
<%
    String title = "hello jsp"
    out.println("<p>" + "hello jsp" + "</p>");
    out.println("<p>" + title + "</p>"); // = servlet java(html)
%>
 
<p><%=title %></p>
 
<h3>request</h3>
<%
// request(요청) : parameter 값을 취득, session을 접근, Object를 전송, encoding 설정 
// HttpServletRequest
// encoding 설정
request.setCharacterEncoding("utf-8");
 
// parameter 값을 취득
// 값 한개 취득(getParameter)
String name = request.getParameter("name");
// url에 "?name=홍길동"을 추가하면,
%>
<p><%=name %></p> <!-- 홍길동 -->
 
<%
// 값 여러개 취득(getParameterValues)
    String[] hobby = request.getParameterValues("hobby");
    // url에 ?hobby=book&hobby=game&hobby=running 추가
    for(int i = 0;i < hobby.length; i++){
    %>
        <p><%=hobby[i] %></p>
    <%    
    }
%>
 
<%
// session에 접근
session = request.getSession(); // 세션 생성 및 얻기
session.setAttribute("visited""1"); // 세션 이름: visited, 세션 값 1 저장
String str = (String)session.getAttribute("visited");
// request.getSession().getAttribute("세션명")의 리턴 타입이 Object이므로 캐스트 연산을 해야한다.
out.println("<h1>" + str + "</h1>"); // 1
 
%>
 
 
 
 
</body>
</html>
cs

 

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
package sample02;
 
import java.io.Serializable;
 
public class Human implements Serializable{
    String name;
    int age;
    
    public Human() {
    }
 
    public Human(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
    
    
    
}
 
cs

 

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
<%@page import="sample02.Human"%>
<%@ 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>
 
<h3>response</h3>
<%
// response: 이동
// response.sendRedirect("이동할 jsp 페이지"): 페이지 이동
// String name = "Tom";
// response.sendRedirect("defaultCopy.jsp?name=" + name + "&age=" + 15);
%>
 
<h3>pageContext</h3>
<
String name = "성춘향";
int age = 16;
 
// 마치 짐을 싸듯이...!
Human human = new Human(name, age);
// human이라는 참조변수가 가리키는 객체를 lady라는 이름으로 담아 보낼 준비
request.setAttribute("lady", human);
 
pageContext.forward("defaultCopy.jsp");
 
 
 
%>
 
</body>
</html>
cs

 

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
<%@page import="sample02.Human"%>
<%@ 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>
 
<h1>defaultCopy.jsp</h1>
 
<%--
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
--%>
<%-- 
<p><%=name %></p> 
<p><%=age %></p> 
 --%>
 
<%
    Human human = (Human)request.getAttribute("lady");
%>
<p>이름:<%=human.getName() %></p>
<p>나이:<%=human.getAge() %></p>
 
</body>
</html>
cs

'Java > JSP, Servlet' 카테고리의 다른 글

JSP와 Servlet 사이에 데이터 주고 받기(json)  (0) 2023.02.08
Servlet 정리  (0) 2023.02.06

Theme. 서블릿(Servlet)이란?

서블릿(Servlet)이란,

클라이언트의 요청을 처리하고, 그 결과를 반환하는 Servlet 클래스의 구현 규칙을 지킨 자바 웹 프로그래밍 기술.

Dynamic Web Page를 만들 때 사용되는 자바 기반의 웹 애플리케이션 프로그래밍 기술.

이라고 할 수 있다.

회사 소개 등과 같이 정적인 페이지의 경우와 다르게 동적인 페이지는 사용자의 다양한 요청에 대해 응답을 해줄 수 있어야 하는데, 서블릿은 이러한 요청과 응답의 흐름을 간단하고 체계적으로 다룰 수 있게 해주는 기술이다.

서블릿은 자바로 구현된 CGI라고 흔히 말한다.

cf) CGV(Common Gateway Interface)란?

 - CGI는 특별한 라이브러리나 도구를 의미하는 것이 아니고, 별도로 제작된 웹서버와 프로그램간의 교환방식이다. CGI방식은 어떠한 프로그래밍언어로도 구현이 가능하며, 별도로 만들어 놓은 프로그램에 HTML의 Get or Post 방법으로 클라이언트의 데이터를 환경변수로 전달하고, 프로그램의 표준 출력 결과를 클라이언트에게 전송하는 것이다. 즉, 자바 어플리케이션 코딩을 하듯 웹 브라우저용 출력 화면을 만드는 방법이다.

 

Theme. Servlet의 동작 원리

  1. 사용자(클라이언트)가 URL을 입력하면 HTTP Request가 Servlet Container로 전송한다.
  2. 요청을 전송받은 Servlet Container는 HttpServletRequest, HttpServletResponse 객체를 생성한다.
  3. web.xml(설정 파일)을 기반으로 사용자가 요청한 URL이 어느 서블릿에 대한 요청인지 찾는다.(매핑할 Servlet 확인)
  4. 서블릿 인스턴스가 없으면  init()메서드를 호출하여 생성하고, 서블릿 컨테이너에 스레드를 생성한다.
  5. 해당 서블릿에서 service메소드를 호출한 후 클리아언트의 GET, POST여부에 따라 doGet() 또는 doPost()를 호출한다.
  6. doGet() 또는 doPost() 메소드는 동적 페이지를 생성한 후 HttpServletResponse객체에 응답을 보낸다.
  7. 응답이 끝나면 destroy() 메서드를 실행하여 HttpServletRequest, HttpServletResponse 두 객체를 소멸시킨다.

 

Theme. Servlet의 주요 특징

  • 클라이언트의 Request에 대해 동적으로 작동하는 웹 애플리케이션 컴포넌트
  • HTML을 사용하여 Response 한다.
  • JAVA의 스레드를 이용하여 동작한다.
  • MVC 패턴에서의 컨트롤러로 이용된다.
  • HTTP 프로토콜 서비스를 지원하는 javax.servlet.http.HttpServlet 클래스를 상속받는다.
  • UDP보다 속도가 느리다.
  • HTML 변경 시 Servlet을 재 컴파일해야 하는 단점이 있다.

 

Theme. Servlet Container(서블릿 컨테이너)

 서블릿 컨테이너란 말 그대로 서블릿을 담고 관리해주는 컨테이너다. 서블릿 컨테이너는 클라이언트의 요청(Request)을 받아주고 응답(Response)할 수 있게, 웹서버와 소켓으로 통신하며 대표적인 예로 톰캣(Tomcat)이 있다. 톰캣은 실제로 웹 서버와 통신하여 JSP(자바 서버 페이지)와 Servlet이 작동하는 환경을 제공해준다. 이후 서블릿 예제들도 톰캣을 사용할 예정이다.

서블릿 컨테이너는 구현되어 있는 servlet 클래스의 규칙에 맞게 서블릿은 관리해주며 클라이언트에서 요청을 하면 컨테이너는 HttpServletRequest, HttpServletResponse 두 객체를 생성하며 post, get여부에 따라 동적인 페이지를 생성하여 응답을 보낸다.

 

HttpServletRequest
http프로토콜의 request정보를 서블릿에게 전달하기 위한 목적으로 사용하며 헤더 정보, 파라미터, 쿠키, URI, URL 등의 정보를 읽어 들이는 메서드와 Body의 Stream을 읽어 들이는 메서드를 가지고 있다.

HttpServletResponse
WAS(Web Application Server)는 어떤 클라이언트가 요청을 보냈는지 알고 있고, 해당 클라이언트에게 응답을 보내기 위한 HttpServleResponse 객체를 생성하여 서블릿에게 전달하고 이 객체를 활용하여 content type, 응답 코드, 응답 메시지 등을 전송한다.

 

init()

서블릿이 처음으로 요청될 때 초기화를 하는 메서드. 클래스를 new 해서 사용하듯 서블릿 클래스도 초기화해주어야 사용이 가능하다. 이렇게 초기화된 서블릿은 싱글톤으로 관리되어 다음에 한번 더 해당 서블릿 클래스를 호출하면 초기화가 다시 일어나는 것이 아니라 기존에 있던 서블릿 클래스를 호출하게 된다.

 

service()

서블릿 컨테이너가 요청을 받고 응답을 내려줄 때 필요한 서블릿의 service 메서드. Servlet interface를 구현한 HttpServlet 클래스의 doGet, doPost 같은 메서드들이 호출됩니다.

 

destroy()

더 이상 사용되지 않는 서블릿 클래스는 주기적으로 서블릿 컨테이너가 destory() 메서드를 호출하여 제거한다. 이렇게 제거된 서블릿은 service 메서드들에 해당하는 모든 스레드들이 종료되거나 사용시간이 오래되어 타임아웃된 경우에 이 클래스를 다시 사용하기 위해서는 init()을 다시 해주어야 한다.

 

< Servlet Container의 역할 >

1. 웹서버와의 통신 지원
서블릿 컨테이너는 서블릿과 웹서버가 손쉽게 통신할 수 있게 해준다. 일반적으로 우리는 소켓을 만들고 listen, accept 등을 해야하지만 서블릿 컨테이너는 이러한 기능을 API로 제공하여 복잡한 과정을 생략할 수 있게 해준다. 그래서 개발자가 서블릿에 구현해야 할 비지니스 로직에 대해서만 초점을 두게끔 도와준다.
 

2. 서블릿 생명주기(Life Cycle) 관리 
서블릿 컨테이너는 서블릿의 탄생과 죽음을 관리한다. 서블릿 클래스를 로딩하여 인스턴스화하고, 초기화 메소드를 호출하고, 요청이 들어오면 적절한 서블릿 메소드를 호출한다. 또한 서블릿이 생명을 다 한 순간에는 적절하게 Garbage Collection(가비지 컬렉션)을 진행하여 편의를 제공한다.

 

3. 멀티쓰레드 지원 및 관리 
서블릿 컨테이너는 요청이 올 때 마다 새로운 자바 쓰레드를 하나 생성하는데, HTTP 서비스 메소드를 실행하고 나면, 쓰레드는 자동으로 죽게된다. 원래는 쓰레드를 관리해야 하지만 서버가 다중 쓰레드를 생성 및 운영해주니 쓰레드의 안정성에 대해서 걱정하지 않아도 된다.
 

4. 선언적인 보안 관리 
서블릿 컨테이너를 사용하면 개발자는 보안에 관련된 내용을 서블릿 또는 자바 클래스에 구현해 놓지 않아도 된다. 일반적으로 보안관리는 XML 배포 서술자에다가 기록하므로, 보안에 대해 수정할 일이 생겨도 자바 소스 코드를 수정하여 다시 컴파일 하지 않아도 보안관리가 가능하다.

 

cf) Servlet 생명주기

 

  1. 클라이언트의 요청이 들어오면 컨테이너는 해당 서블릿이 메모리에 있는지 확인하고, 없을 경우 init()메소드를 호출하여 적재한다. init()메소드는 처음 한번만 실행되기 때문에, 서블릿의 쓰레드에서 공통적으로 사용해야하는 것이 있다면 오버라이딩하여 구현하면 된다. 실행 중 서블릿이 변경될 경우, 기존 서블릿을 파괴하고 init()을 통해 새로운 내용을 다시 메모리에 적재한다.
  2. init()이 호출된 후 클라이언트의 요청에 따라서 service()메소드를 통해 요청에 대한 응답이 doGet()가 doPost()로 분기된다. 이때 서블릿 컨테이너가 클라이언트의 요청이 오면 가장 먼저 처리하는 과정으로 생성된 HttpServletRequest, HttpServletResponse에 의해 request와 response객체가 제공된다.
  3. 컨테이너가 서블릿에 종료 요청을 하면 destroy()메소드가 호출되는데 마찬가지로 한번만 실행되며, 종료시에 처리해야하는 작업들은 destroy()메소드를 오버라이딩하여 구현하면 된다.

 

Theme. 여러 예제들 및 설명

 

서블릿 컨테이너로 톰캣을 사용하고, 이클립스에서 Dynamic Web Project를 생성하고, html, java 파일(서블릿 작성), web.xml 파일을 만든다.

 

먼저, web.xml 파일에서 서블릿을 정의하는 방법에 대해 알아보자.

web.xml은 서버가 시작될 때 웹서버가 사용하는 (환경)설정 파일인데, 웹 애플리케이션 서비스 실행에 관한 전반적인 내용을 정의하는 환경설정 파일이다.

서버에서 서블릿 실행에 관한 정보를 설정할 때 web.xml에 <servlet> 태그로 설정한다. 

아래와 같이 작성할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>sample01</display-name>
  
<!--  설정 부분 --> 
  <servlet>
      <servlet-name>hello</servlet-name> 
      <servlet-class>sample01.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/location</url-pattern>
  </servlet-mapping>
  
</web-app>
cs

<servlet> 태그에서,

<servlet-name> 태그: 해당 서블릿을 참조할 때 사용할 이름

<servlet-class> 태그: 서블릿으로 사용할 서블릿 클래스 ( "패키지명.클래스명" 형식으로 작성)

 

<servlet-mapping> 태그에서,

<servlet-name> 태그: 매핑할 서블릿의 이름

<url-pattern> 태그: 매핑할 url 패턴

 

이제, doGet()과 doPost()이 포함된 서블릿을 작성해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package sample01;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doGet");
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doPost");
    }
    
    
}
 
cs

그리고, index.html 파일은 다음과 같다.

 

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<!--  
        Servlet = Server + Applet
        
        get:     parameter가 오픈
        post:    parameter가 보이지 않음(보안의 측면)
-->
 
<form action="location" method="get"> <!-- doGet으로! -->
    <input type="submit" value="get이동"> <!-- doPost으로! -->
</form>
<br>
<form action="location" method="post">
    <input type="submit" value="post이동">
</form>
<br>
 
<a href="location">a tag move</a> <!-- get  -->
<br><br>
 
<button type="button" onclick="move()">JS 이동</button>
 
<!-- get  -->
<script type="text/javascript"> 
function move(){
    location.href="location"
}
 
 
 
</script>
 
</body>
</html>
cs

<form> 의 action 속성, <a>의 href 속성, location.href=""를 이용하여 이동하였다.

 

2번째 예제) 사용자가 입력한 값을 넘겨받아 html 문서를 만듦

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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>sample02</display-name>
  
  <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>sample02.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>sample</servlet-name>
      <servlet-class>sample02.SampleServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>sample</servlet-name>
      <url-pattern>/sample</url-pattern>
  </servlet-mapping>
  
  
  
  
  
</web-app>
cs
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
package sample02;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HelloServlet extends HttpServlet{
 
    @Override       // request.getParameter("id") -> JSP
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        /*
              servlet -> java코드에 html 태그를 넣어서 사용 --> Controller로 사용
              
              JSP -> html 코드에 java가 섞여있다.
        */
        
//        아래 코드와 같이 사용하지는 않는다. 너무 복잡하니까
        
        resp.setContentType("text/html; charset=utf-8");
        
        PrintWriter pw = resp.getWriter();
        
        pw.println("<html>");
        
        pw.println("<head>");
            pw.println("<title>제목입니다</title>");
        pw.println("</head>");
        
        pw.println("<body>");
            pw.println("<h1>Welcome to HelloServlet</h1>");
            pw.println("<p>hello Servlet</p>");
            
            pw.println("<a href='index.html'>index.html</a>");
        pw.println("</body>");
        
        pw.println("</html>");
        
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }
    
}
 
cs

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package sample02;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class SampleServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String name = req.getParameter("name");
        String sAge = req.getParameter("age");
        int age = Integer.parseInt(sAge);
        
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter pw = resp.getWriter();
 
        pw.println("<html>");
 
        pw.println("<head>");
        pw.println("<title>제목입니다</title>");
        pw.println("</head>");
 
        pw.println("<body>");
        
        pw.println("<p>name: " + name + "</p>");
        pw.println("<p>age: " + age + "</p>");
         
        pw.println("</body>");
 
        pw.println("</html>");
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        req.setCharacterEncoding("utf-8"); // 한글 깨지는 것 해결방법
        
        String name = req.getParameter("name");
        String sAge = req.getParameter("age");
        int age = Integer.parseInt(sAge);
        
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter pw = resp.getWriter();
 
        pw.println("<html>");
 
        pw.println("<head>");
        pw.println("<title>제목입니다</title>");
        pw.println("</head>");
 
        pw.println("<body>");
        
        pw.println("<p>name: " + name + "</p>");
        pw.println("<p>age: " + age + "</p>");
         
        pw.println("</body>");
 
        pw.println("</html>");
    }
 
}
 
cs
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<form action="hello" method="get">
    <input type="submit" value="이동">
</form>
 
<br><br>
 
<form action="sample" method="get">
이름:<input type="text" name="name"><br>
나이:<input type="text" name="age"><br><br>
<input type="submit" value="sample get로 이동">
</form>
<br><br>
 
<form action="sample" method="post">
이름:<input type="text" name="name"><br>
나이:<input type="text" name="age"><br><br>
<input type="submit" value="sample post로 이동">
</form>
 
</body>
</html>
cs

3번째 예제) 2번째 예제와 같은 상황인데, 값을 여러개 입력받아 html 문서를 만듦

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>sample03</display-name>
  
  <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>sample03.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
  
  
</web-app>
cs

 

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
53
54
55
56
57
58
59
60
61
package sample03;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HelloServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
 
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
 
    }
 
    public void doProc(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 
        String[] hobby = req.getParameterValues("hobby"); // 2개 이상의 데이터를 받기 위함
        String[] url = req.getParameterValues("url"); // 2개 이상의 데이터를 받기 위함
 
        resp.setContentType("text/html; charset=utf-8");
 
        PrintWriter pw = resp.getWriter();
 
        pw.println("<html>");
 
        pw.println("<head>");
        pw.println("<title>제목입니다</title>");
        pw.println("</head>");
 
        pw.println("<body>");
 
        pw.println("<p>취미</p>");
        if(hobby != null)
            for (int i = 0; i < hobby.length; i++) {
                pw.println("<p>" + hobby[i] + "</p>");
            }
 
        pw.println("<p>사이트</p>");
        if(url != null)
        for (int i = 0; i < url.length; i++) {
            pw.println("<p>" + url[i] + "</p>");
        }
 
        pw.println("</body>");
 
        pw.println("</html>");
 
    }
 
}
 
cs

 

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<form action="hello" id="frm">
<h3>취미</h3>
<input type="checkbox" name="hobby" value="picture">그림그리기
<input type="checkbox" name="hobby" value="game">게임하기
<input type="checkbox" name="hobby" value="movie">영화보기
<br><br>
 
<h3>좋아하는 사이트</h3>
<select name="url" multiple="multiple">
    <option value="naver">네이버</option>
    <option value="google">구글</option>
    <option value="zum"></option>
</select>
 
<button type="button">send</button>
 
</form>
 
<script type="text/javascript">
$(document).ready(function(){
    
    $("button").click(function(){
        $("#frm").submit(); // action 위에서 적어줬으니까
//         $("#frm").attr("action", "hello").submit(); // action 위에서 안 적어줬을 때
        
    });
});
 
 
</script>
 
 
</body>
</html>
cs

 

4번째 예제) 사용자로부터 입력을 받아 HelloServlet.java, WorldServlet.java 파일을 모두 거쳐 응답해줌

 

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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>sample04</display-name>
  
  <!-- HelloServelt -->
  <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>sample04.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
  <!-- WorldServelt -->
  <servlet>
      <servlet-name>world</servlet-name>
      <servlet-class>sample04.WorldServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>world</servlet-name>
      <url-pattern>/world</url-pattern>
  </servlet-mapping>
  
  
  
</web-app>
cs

 

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
package dto;
 
import java.io.Serializable;
 
public class Human implements Serializable {
    
    private String name;
    private int age;
    private String address;
    
    public Human() {}
 
    public Human(String name, int age, String address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
    
    
    
    
    
    
}
cs

 

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
53
54
55
56
57
58
59
60
61
62
63
64
package sample04;
 
import java.io.IOException;
import java.net.URLEncoder;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dto.Human;
 
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
    }
    
    public void doProc(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doProc()");
        
        req.setCharacterEncoding("utf-8");
        
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        String address = req.getParameter("address");
        
        /*
         * 첫번째 방법(response 소속의 sendRedirect 사용)
        // 한글의 경우에는 인코딩을 처리해 주어야 한다.
        String ename = URLEncoder.encode(name);
        String eaddress = URLEncoder.encode(name);
        
//        resp.sendRedirect("world"); // 맵핑된 world로 이동
        
        resp.sendRedirect("world?name=" + ename + "&age=" + age + "&address=" + eaddress);
     
        */
        
//        두번째 방법(RequestDispatcher 소속의 forward 사용)
        Human h = new Human(name, age, address);
        
        // 짐 싸!
        req.setAttribute("human", h); // h 객체를 "human"이라는 이름으로!
        
        // 이동
        req.getRequestDispatcher("world").forward(req, resp);
//        resp.sendRedirect("world"); --> 단순이동
        
        
        
        
        
        
    }
    
}
 
cs

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package sample04;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dto.Human;
 
public class WorldServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProc(req, resp);
    }
 
    public void doProc(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 첫번째 방법에서 사용
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        String address = req.getParameter("address");
        */
        
        // 두번째 방법
        // 짐을 푼다
        Human human = (Human)req.getAttribute("human");
        
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
 
        PrintWriter pw = resp.getWriter();
 
        pw.println("<html>");
 
        pw.println("<head>");
        pw.println("<title>World입니다</title>");
        pw.println("</head>");
 
        pw.println("<body>");
        
        pw.println("<h1>World</h1>");
        /*
        pw.println("<p>이름: " + name + "</p>");
        pw.println("<p>나이: " + age + "</p>");
        pw.println("<p>주소: " + address + "</p>");
        */
        
        pw.println("<p>이름: " + human.getName() + "</p>");
        pw.println("<p>나이: " + human.getAge() + "</p>");
        pw.println("<p>주소: " + human.getAddress() + "</p>");
        
        
        pw.println("</body>");
 
        pw.println("</html>");
 
    }
    
    
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<form action="hello" method="get">
이름:<input type="text" name="name"><br>
나이:<input type="text" name="age"><br>
주소:<input type="text" name="address"><br>
<input type="submit" value="전송">
</form>
 
</body>
</html>
cs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

자료 참고 및 출처: https://mangkyu.tistory.com/14

 

[JSP] 서블릿(Servlet)이란?

1. Servlet(서블릿) 서블릿을 한 줄로 정의하자면 아래와 같습니다. 클라이언트의 요청을 처리하고, 그 결과를 반환하는 Servlet 클래스의 구현 규칙을 지킨 자바 웹 프로그래밍 기술 간단히 말해서,

mangkyu.tistory.com

https://coding-factory.tistory.com/742

 

[Web] 서블릿(Servlet)이란 무엇인가? 서블릿 총정리

서블릿(Servlet)이란? 서블릿이란 Dynamic Web Page를 만들 때 사용되는 자바 기반의 웹 애플리케이션 프로그래밍 기술입니다. 웹을 만들때는 다양한 요청(Request)과 응답(Response)이 있기 마련이고 이 요

coding-factory.tistory.com

 

+ Recent posts