본문 바로가기
JS

AJAX(바닐라 js)와 서블릿(Servlet) 간의 통신

by seeker00 2021. 7. 7.

AJAX를 이용해 GET 방식의 request를 서블릿 매핑 주소로 보내고, 서블릿에서 응답을 받아오기

document.addEventListener("DOMContentLoaded", function() {
    ...(생략, 매개변수로 보낼 값을 가져온다)
    ajaxGet(id, type);    
}

const ajaxGet = function(id, type) {
     let oReq = new XMLHttpRequest();
     oReq.addEventListener("load", function() { // response응답 도착
       if (this.status == 200) {
       console.log(this, this.responseText); // 성공, 응답코드 200
       } else {
       console.log(this.status); // 그 외
       }
     });    
     oReq.open("GET", "ex?id="+ id +"&type="+ type);//parameter를 붙여서 요청을 작성
     oReq.send();// 전달
    }

 

서블릿 파일

@WebServlet("/ex")
public class ExampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public  ExampleServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        String type = request.getParameter("type");

        // 수행할 로직 작성
        int result = 1; // 성공하였을 경우 가정

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");// 보내고 싶은 응답 데이터에 따라서 text/html 혹은 application/json을 이용한다
        PrintWriter out = response.getWriter();

        if (result==1) {
            out.print("success");
            out.close();
        }
        out.print("fail"); // 내부 로직 실패
        out.close();
    }
}

페이지를 리다이렉트하는 등의 추가 요청이 없이 응답만 전달되기 때문에, 클라이언트 화면에서는 콘솔에 로그가 찍히는 것과 그 외 자신이 작성한 자바스크립트 코드(클라이언트단에서 수행되는 로직)만 구현된다.

  • {본인의 프로젝트 root 주소}/ex 로 이동하면, 서블릿에서 보내는 응답 결과를 브라우저 화면에서 확인할 수 있다.

 

 

참고) 바닐라 js로 AJAX 사용하기 https://teserre.tistory.com/7

'JS' 카테고리의 다른 글

DOM(Document Object Model)  (0) 2021.07.07
특정 버튼들의 클릭 이벤트 리스너  (0) 2021.07.07
AJAX 통신  (0) 2021.07.06