Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
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
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

[JSP/Servlet] 서블릿과 Ajax로 통신 후에 결과를 HTML로 뿌려주기. 본문

프로그래밍/Jsp_Servlet

[JSP/Servlet] 서블릿과 Ajax로 통신 후에 결과를 HTML로 뿌려주기.

David 리 2024. 1. 21. 18:10

[Ajax]란?

Ajax란 Asynchronous JavaScript and XML의 약자이다.

빠르게 동작하는 동적 웹 페이지 제작을 위해 사용하는 클라이언트 통신 기법입니다.

웹 페이지 전체를 로딩하지 않고 일부분만을 로딩할 수 있습니다.

개념은 짧게 설명을 마치도록 하겠습니다.

 

이번 시간에 해 볼 연습은

서블릿(Servlet)과 Ajax통신 후에 반환되는 데이터를 JSP로 내보내 HTML화면에 뿌리기입니다.

 

먼저

서블릿 입니다.

[AjaxServlet.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
38
package controller;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(urlPatterns = {"/getHtmlAjax.do"})
public class AjaxServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
//        super.doGet(req, resp);
        resp.setContentType("text/html; charset=UTF-8");
        process(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
        
    }
 
    public void process(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
        System.out.println("에이잭스 호출!!!");
        req.getRequestDispatcher("/ajax/getAjaxHTML.jsp").forward(req, res);
        
    }
    
}
 
cs

17Line : Ajax요청 시 GET메소드로 구현했습니다. 따라서 doGet()를 호출합니다.

20Line : response객체에 콘텐트타입 속성을  "UTF-8"로 주었습니다. 이것으로 응답데이터가 깨짐현상을 방지할 수 있습니다.

33 ~ 38Line : Ajax통신 후에 HTML로 붙여줄 JSP페이지 입니다.

 

 

 

[getAjaxHTML.jsp]

1
2
3
4
5
6
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<p>여기는 ajax통신 후 HTML로 붙일 데이터입니다.</p>
<p>런던은 영국의 수도이죠.</p>
<p>영국은 축구의 종주국으로도 유명합니다. 메이저리그인 프리미어리그가 있습니다.</p>
<strong>그리고 리그에서 수많은 팀들이 존재합니다. 그 중에서 맨체스터 유나이티드, 리버풀, 아스날, 첼시, 토트넘..등 이 이외에도 여러팀들도 존재합니다.</strong>
cs

Ajax문법에는 라이프사이클이 존재합니다.

제가 사용할 메소드는 'success'로 요청 성공시 호출됩니다. 이 메소드에서 getAjaxHTML.jsp 태그를 붙여줄 겁니다.

 

한편, Ajax 라이프 사이클에는 'beforeSend'라는 메소드가 있습니다. 통신 전에 실행되는 메소드입니다.

 

 

 

[ajaxTest.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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>ajax연습</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
{
  box-sizing: border-box;
}
 
body {
  font-family: Arial, Helvetica, sans-serif;
}
 
/* Style the header */
header {
  background-color: #666;
  padding: 30px;
  text-align: center;
  font-size: 35px;
  color: white;
}
 
/* Create two columns/boxes that floats next to each other */
nav {
  float: left;
  width: 30%;
  height: 300px; /* only for demonstration, should be removed */
  background: #ccc;
  padding: 20px;
}
 
/* Style the list inside the menu */
nav ul {
  list-style-type: none;
  padding: 0;
}
 
article {
  float: left;
  padding: 20px;
  width: 70%;
  background-color: #f1f1f1;
  height: 300px; /* only for demonstration, should be removed */
}
 
/* Clear floats after the columns */
section::after {
  content: "";
  display: table;
  clear: both;
}
 
/* Style the footer */
footer {
  background-color: #777;
  padding: 10px;
  text-align: center;
  color: white;
}
 
/* Responsive layout - makes the two columns/boxes stack on top of each other instead of next to each other, on small screens */
@media (max-width: 600px) {
  nav, article {
    width: 100%;
    height: auto;
  }
}
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        url : "/seesionPractice/getHtmlAjax.do",     // 서버통신 URL
        method : 'get',                               // 메소드 방식
        type : "html",                                // 응답(response) 데이터 형식
        data : "aa",                                  // 서버와 통신 시 보낼 파라미터
        success : function(data) {                    // 서버와 통신 후에 비즈니스 로직 작성하는 메소드(라이프 사이클)
            $('#london').html(data);
        }, 
        error : function(req, status, error) {        // 서버와 통신 중에 에러가 나는 메소드
            console.log('req', req);
            console.log('status', status);
            console.log('error', error);
            alert('통신 중 오류가 났습니다. 코드'+req.statusText)
        }
    });
});
 
</script>
 
<h2>CSS Layout Float</h2>
<p>In this example, we have created a header, two columns/boxes and a footer. On smaller screens, the columns will stack on top of each other.</p>
<p>Resize the browser window to see the responsive effect (you will learn more about this in our next chapter - HTML Responsive.)</p>
 
<header>
  <h2>Cities</h2>
</header>
 
<section>
  <nav>
    <ul>
      <li><a href="#">London</a></li>
      <li><a href="#">Paris</a></li>
      <li><a href="#">Tokyo</a></li>
    </ul>
  </nav>
  
  <article>
    <h1 id="london">London</h1>
    <!-- <p>London is the capital city of England. It is the most populous city in the  United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
    <p>Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.</p> -->
        ajax호출해서 붙여줄 부분~
  </article>
</section>
 
<footer>
  <p>Footer</p>
</footer>
 
</body>
</html>
cs

 

78 ~ 93Line : 전체 기본적인 Ajax문법입니다. 사용한 라이프 사이클로는 'success'와 'error'가 있습니다.

82Line : 통신 시 필요한 파라미터인데, 여기에서는 아무 의미가 없습니다.

83 ~ 85Line : 위에서 언급한 Ajax통신하고 JSP를 HTML로 붙입니다.

115Line : HTML로 붙여지는 부분입니다.

 

 

 

[결과]