[Servlet] 서블릿 응답

sang·2024년 1월 30일

서블릿 응답

  • doGet() or doPost() 메소드
  • javax.servlet.http.HttpServletResponse 객체 이용
  • setContentType(): MIME-TYPE 지정
  • 자바 I/O 스트림을 이용한 클라이언트-서블릿 통신

마임 타입 MIME TYPE

톰캣 컨테이너에서 미리 설정해 놓은 데이터 종류
서블릿에서 자바 I/O 스트림 클래스를 이용해 웹 브라우저로 데이터 전송 시 사용
웹 브라우저의 더 빠른 처리를 위해 데이터 종류를 미리 알려줄 때 사용

  • HTML 전송
    text/html
  • 일반 텍스트 전송
    text/plain
  • XML 데이터 전송
    application/xml

새로운 데이터 종류 지정

CATALINA_HOME\conf\web.xml에 추가



데이터 전송

전송 방식과 메소드

  • GET
    URL 주소에 데이터를 붙여서 전송하는 기본 전송 방식
    보안 취약
    최대 255가지 데이터 전송 가능
    빠른 처리 속도
    doGet() 메소드로 처리

  • POST
    데이터를 TCP/IP 프로토콜 데이터 body 영역에 숨겨서 전송
    보안 유리
    보안 관련 데이터 전송에 사용
    전송 데이터 용량 무제한
    느린 처리 속도
    doPost() 메소드로 처리


단일 전송 방식 처리

실습 코드

pro06/WebContent/login.html

<!DOCTYPE html>
<html>
<head>...</head>
<body>
  <form name="loginForm" method="post" action="login" encType="UTF-8"> 
    아이디:<input type="text" name="user_id"><br>
    비밀번호:<input type="password" name="user_pw"><br>
    <input type="submit" value="로그인"> <input type="reset" value="다시 입력">
  </form>
</body>
</html>

pro06/src/sec03/ex01/LoginServlet.java

package sec03.ex01;
...
 
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
  public void init() throws ServletException {
    System.out.println("init 메서드 호출");
  }
 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    String user_id = request.getParameter("user_id");
    String user_pw = request.getParameter("user_pw");
    System.out.println("아이디:" + user_id);
    System.out.println("비밀번호:" + user_pw);
  }

  public void destroy() {
    System.out.println("destroy 메서드 호출");
  }
}

혼합 방식 처리

  1. doGet() or doPost() 메소드 처리
  2. doHandle() 메소드 호출
  3. doHandle() 메소드 처리

실습 코드

pro06/WebContent/login.html

<!DOCTYPE html>
<html>
<head>...</head>
<body>
  <form name="loginForm" method="get" action="login" encType="UTF-8">
    아이디:<input type="text" name="user_id"><br>
    비밀번호:<input type="password" name="user_pw"><br>
    <input type="submit" value="로그인"> <input type="reset" value="다시 입력">
  </form>
</body>
</html>

pro06/src/sec03/ex02/LoginServlet.java

package sec03.ex02;
...

public class LoginServlet extends HttpServlet {
  public void init() throws ServletException {
    System.out.println("init 메서드 호출");
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("doGet 메서드 호출");
    doHandle(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("doPost 메서드 호출");
    doHandle(request, response);
  }
  
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    String user_id = request.getParameter("user_id");
    System.out.println("doHandle 메서드 호출");
    String user_pw = request.getParameter("user_pw");
    System.out.println("아이디:" + user_id);
    System.out.println("비밀번호:" + user_pw);
  }

  public void destroy() {
    System.out.println("destroy 메서드 호출");
  }
}


실습 예제

로그인

pro06/WebContent/test01/login.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>로그인 창</title>
</head>
<body>
  <form name="frmLogin" method="post" action="/pro06/loginTest" encType="UTF-8">
    아이디 :<input type="text" name="user_id"><br>
    비밀번호:<input type="password" name="user_pw"><br>
    <input type="submit" value="로그인"> <input type="reset" value="다시 입력">
  </form>
</body>
</html>

pro06/src/sec04/ex01/LoginTest.java

package sec04.ex01;

@WebServlet("/loginTest")
public class LoginTest extends HttpServlet
{
  public void init()
  {
    System.out.println("init 메서드 호출");
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    String id = request.getParameter("user_id");
    String pw = request.getParameter("user_pw");

    System.out.println("아이디 : "+ id);
    System.out.println("패스워드 : "+ pw);

    if(id!= null &&(id.length()!=0)) {
      if(id.equals("admin")) {
        out.print("<html>");
        out.print("<body>");
        out.print( "<font size='12'>관리자로 로그인 하셨습니다!! </font>" );
        out.print("<br>");
        out.print("<input type=button value='회원정보 수정하기' />");
        out.print("<input type=button value='회원정보 삭제하기' />");
        out.print("</body>");
        out.print("</html>");
      } else {
        out.print("<html>");
        out.print("<body>");
        out.print( id +" 님!! 로그인 하셨습니다." );
        out.print("</body>");
        out.print("</html>");
      }
    }else{
      out.print("<html>");
      out.print("<body>");
      out.print("ID와 비밀번호를 입력하세요!!!" ) ;
      out.print("<br>");
      out.print("<a href='http://localhost:8090/pro06/test01/login.html'> 로그인 창으로 이동 </a>");
      out.print("</body>");
      out.print("</html>");
    }
  }
  public void destroy() {
    System.out.println("destroy 메서드 호출");
  }
}

구구단

pro06/WebContent/test01/gugu.html

<!DOCTYPE html>
<html>
<head>
  <title>단수 입력창</title>
</head>
<body>
  <h1>출력할 구구단의 수를 지정해 주세요.</h1>
  <form method="get" action="/pro06/guguTest">
    출력할 구구단 :<input type=text name="dan" /> <br>
    <input type="submit" value="구구단 출력">
  </form>
</body>
</html>

pro06/src/sec04/ex01/GuguTest.java

package sec04.ex01;
...

@WebServlet("/guguTest")
public class GuguTest extends HttpServlet {
  public void init() {
    System.out.println("init 메서드 호출");
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    int dan = Integer.parseInt(request.getParameter("dan"));
    out.print(" <table border=1 width=800 align=center>");
    out.print("<tr align=center bgcolor='#FFFF66'>");
    out.print("<td colspan=2>" + dan + " 단 출력 </td>");
    out.print("</tr>");
     
    for (int i = 1; i < 10; i++) {
      /* 테이블 배경 교대 색상 지정 */
      if (i % 2 == 0) { out.print("<tr align=center bgcolor='#ACFA58'> "); }
      else { out.print("<tr align=center bgcolor='#81BEF7'> "); }
      
      out.print("<td width=400>");
      out.print(dan + " * " + i);
      out.print("</td>");
      out.print("<td width=400>");
      out.print(i * dan);
      out.print("</td>");
      out.print("</tr>");
    }
    out.print("</table>");
  }
  
  public void destroy() {
    System.out.println("destroy 메서드 호출");
  }
}


*자바 웹을 다루는 기술

profile
CS 메모장

0개의 댓글