48. Servlet(2)

sumin·2023년 9월 11일
0

아카데미

목록 보기
49/82
post-thumbnail

post 방식으로 입력받기

<!-- Html -->
<!-- 동일한 파라미터를 2개이상 요청하기   -->
    <div>
      <form method="post" action="/servlet/request">
        <div>
        <select name="tel">
          <option value="010">010</option>  <!--value 가 없으면 값을 전달해 주지 않음  -->
          <option value="02">02</option>
          <option value="031">031</option>
        </select>
        <input type="text" name="tel">
        <input type="text" name="tel">        
        </div>
        <div>
          <input type="checkbox" name="hobbies" value="travel" id="travel">
          <label for="travel">여행</label>
          <input type="checkbox" name="hobbies" value="game" id="game">
          <label for="game">게임</label>
          <input type="checkbox" name="hobbies" value="golf" id="golf">
          <label for="golf">골프</label>
        </div>
        <div>
        <button type="submit">제출</button>
        </div>
      </form>
    </div>
@WebServlet("/request")
public class RequestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestServlet() {
        super();
        
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    
    // 1. 요청을 UTF-8로 인코딩한다. . 
    request.setCharacterEncoding("UTF-8");
    
    // 2. 동일한 요청 파라미터가 2개 이상 전달되는 경우 getParameterValues()메소드를 이용해서 요청 파라미터들를 배열로 받는다.
    String[] tel = request.getParameterValues("tel");
    String[] hobbies = request.getParameterValues("hobbies");
    
    System.out.println(Arrays.toString(tel));
    System.out.println(Arrays.toString(hobbies));

입력 받아서 보여주기 (Response)

package ex03_response;

import java.io.IOException;
import java.io.PrintWriter;

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 ResponseServlet
 */
@WebServlet("/response")
public class ResponseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ResponseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  
    // 모든 작업은 doGet에서 해라 get과 post 를 구별하지 말아라 	  
	  // 1. 요청 인코딩
	  request.setCharacterEncoding("UTF-8");
	  
	  //2. 요청 파라미터
	  String gender = request.getParameter("gender");
	  String domain = request.getParameter("domain");
	  String content = request.getParameter("content");
	  String region = request.getParameter("region");
	  
	  /*
	   * 응답 (Response)
	   * 1. 서버가 클라이언트에게 데이터를 보내는 것을 의미한다. 
	   * 2. HttpServletResponse 클래스가 응답을 처리한다.  
	   * 3. 응답할 데이터의 타입(MIME TYPE)을 결정하고 응답한다. 
	   *   1) text/html         : 태그를 만들어서 반환하는 경우 
	   *   2) application/xml   : XML을 반환하는 경우   
	   *   3) application/json : JSON을 반환하는 경우 
	   */
	  
	  //3. 응답 데이터의 타입 설정과 인코딩 설정
	  response.setContentType("text/html; charset=UTF-8");
	  
	  // 4. 응답 스트림 생성( 문자 기반의 출력 스트림인 Writer 생성)
	  // IOException 예외 처리가 필요하디만  doGet() 메소드는 IOException 처리를 이미 하고 있다. 
	  PrintWriter out = response.getWriter();
	  
	  // 5. 응답하기 (온전한 웹 페이지)

	  out.println("<!DOCTYPE html>");
    out.println("<html lang=\"ko\">");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\">");
    out.println("<title>페이지제목</title>");
    out.println("<style>");
    out.println(".wrap {");
    out.println("   background-color: #a0a0a0;");
    out.println("}");
    out.println("</style>");
    out.println("</head>");
    out.println("<body>");
    out.println("<div class=\"wrap\">");
    out.println("<h1>요청 파라미터</h1>");
    out.println("<ul>");
    out.println("<li>성별: " + gender + "</li>");
    out.println("<li>도메인: " + domain + "</li>");
    out.println("<li><pre>" + content + "</pre></li>");
    out.println("<li>지역:" + region + "</li>");
    out.println("</ul>");
    out.println("</div>");
    out.println("</body>");
    out.println("</html>");	  
	  out.flush();
	  out.close();	  	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Forward

forward1

package ex04_forward;

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 Forward
 */
@WebServlet("/forward1")
public class Forward1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Forward1() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  
	  /*
	   * forward
	   * 1. 다른 경로로 이동하는 방식 중 하나이다. 
	   * 2. 다른 경로로 직접 요청 파라미터를 이동시킨다. 
	   * 3. 경로를 작성할 때 URLMappting 만 작성한다. (Contextpath는 작성하지 않는다. ) 
	   */
	  
	  // 요청의 전달 객체 생성
	  RequestDispatcher dispatcher = request.getRequestDispatcher("/forward2");      
	  	  
	  //전달 (요청과 응답을 모두 전달함)
	  dispatcher.forward(request, response);	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

forward2

package ex04_forward;

import java.io.IOException;
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 Forward2
 */
@WebServlet("/forward2")
public class Forward2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Forward2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	  // 요청 인코딩
	  request.setCharacterEncoding("UTF-8");
	  
	  // 요청 파라미터 
	  String name = request.getParameter("name");
	  
	  System.out.println("forward: " + name);
	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

Redirect

redirect1

package ex05_redirect;

import java.io.IOException;
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 Redirect1
 */
@WebServlet("/redirect1")
public class Redirect1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Redirect1() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  /*
     * redirect
     * 1. 다른 경로로 이동하는 방식 중 하나이다. 
     * 2. 서버가 다른 경로를 응답하면 클라이언트가 해당 경로로 직접 이동하는 방식이다. 
     * 3. 경로를 작성할 때 Contextpath와 URLMappting을 모두 작성한다.  
     */
	  
	  // redirect할 경로를 응답함
	  response.sendRedirect("/servlet/redirect2");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

redirect2

package ex05_redirect;

import java.io.IOException;
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 Redirect2
 */
@WebServlet("/redirect2")
public class Redirect2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Redirect2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 //1. 요청 인코딩
	  request.setCharacterEncoding("utf-8");
	  
	  //2. 요청 파라미터
	  String name = request.getParameter("name");
	  System.out.println("redirect: " + name);
	      
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

XML

Html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
  src="https://code.jquery.com/jquery-3.7.1.min.js"
  integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
  crossorigin="anonymous"></script>
</head>
<body>

  <div>
    <div> 
      <input type="text" id="name" placeholder="이름">    
    </div>
    <div>
      <input type="text" id="age" placeholder="나이">
    </div>
    <div>
      <button type="button" id="btn1">XML요청</button>
    </div>
    <div id="content1"></div>
  </div>  
  
  <script>
    $('#btn1').click(function() {
      $.ajax({
        /* 요청 */
        type:'get',
        url: '/servlet/getXML',
        data: 'name=' + $('#name').val() + '&age=' + $('#age').val(),   
        /* 응답 */
        datatype:'xml', 
        success: function(resData) {  /// resData는 <person><name>alice</name><age>30</age></person>형태이다. 
          $('#content1').empty();
          var ul = $('<ul>');
          ul.append($('<li>').text($(resData).find('name').text()));
          ul.append($('<li>').text($(resData).find('age').text()));
          $('#content1').append(ul);
          
          },
        erorr: function(jqXHR){
          alter(jqXHR.status + '(' + jqXHR.statusText + ')');
        }
      })
      
    })  
  </script>
  
  <hr>
  
  <div>
  <form id="frm">
    <div> 
        <input type="text" name="title" placeholder="제목">    
      </div>
      <div>
        <input type="text" name="writer" placeholder="작성자">
      </div>
      <div>
        <button type="button" id="btn2">JSON요청</button>
      </div>
      <div id="content1"></div>  
  </form>
  <div id="content2"> </div>
  </div>
  
  <script>
  $('#btn2').click(function() {
    $.ajax({
      type:'get',
      url: '/servlet/getJSON',
      data: $('#frm').serialize(), // <form> 태그의 모든 입력 요소들을 파라미터로 보낸다 이때 입력 요소들은 name
      /* 응답 */
      dataType :'json',
      success: function(resData) { // resData는 {"writer": "관리자 ,"title" : "공지사항"} 형태
       var str = '';
       str += '<h4>' + resData.title + '</h4>';
       str += '<h4>' + resData.writer + '</h4>';
       $('#content2').html(str);
      
      },
      error: function(jqXHR) {
        alter(jqXHR,statue + '(' + jqXHR.statusText + ')');
      }
    })
  })
  </script>
</body>
</html>

servlet

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.JSONObject;
import org.json.XML;

/**
 * Servlet implementation class XMLServlet
 */
@WebServlet("/getXML")
public class XMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public XMLServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 요청 인코딩
	  request.setCharacterEncoding("UTF-8");
	  
	  //2.요청 파라미터 
	  String name = request.getParameter("name");
	  String strAge = request.getParameter("age");
	  int age = 0;
	  if(strAge != null && !strAge.isEmpty()) {
	    age = Integer.parseInt(strAge);
	  }
	   //3. XML 만들기 
	  //{"person":{"name:":"alice", "age": 30}}를 생성한 뒤 XML 태그 형식으로 변환
	  /*
	   * <?xml version="1.0" encoding="UTF-8"?>
     * <person>
     *   <name>alice</name>
     *   <age>30</age>
     * </person>
	   */
	  
	  JSONObject person = new JSONObject();
	  person.put("name", name);
	  person.put("age", age);
	  JSONObject resJSON = new JSONObject();
	  resJSON.put("person", person);
	  
	  String responseXML = XML.toString(resJSON);


	  // 4. 응답 데이터 타입과 인코딩
	  response.setContentType("application/xml; charset=UTF-8");
	  
	  //5. 응답 스트림 생성
	  PrintWriter out = response.getWriter();
	  
	  // 6. 응답
	  out.println(responseXML);//$.ajax({success: function(resData){}...)
	                            // function의 매개변수 resData
	  out.flush(); 
	  out.close();
	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

JSON

servlet

package ex06_ajax;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.JSONObject;

/**
 * Servlet implementation class JSONServlet
 */
@WebServlet("/getJSON")
public class JSONServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JSONServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  // 1. 인코딩한다. 
	  request.setCharacterEncoding("UTF-8");
	  
	  //2. 요청 파라미터
	  String title = request.getParameter("title");
	  String writer = request.getParameter("writer");
	  
	  ///3 . JSON 만들기
	  // {"title":"공지사항", "writer":"관리자"}
	  JSONObject responseJSON = new JSONObject();
	  responseJSON.put("title", title); 
	  responseJSON.put("writer", writer); 
	  
	  // 4. 응답 데이터 타입과 인코딩
	  response.setContentType("application/json; charset=UTF-8");
	  
	  // 5. 응답스트림 생성
	  PrintWriter out = response.getWriter();
	  
	  //6. 응답
	  out.println(responseJSON);
	  out.flush();
	  out.close();
	  
	  String str = "{\"writer\":\"" + writer + "\" ,\"title\":" + title + "\"}";
	  	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
profile
백엔드 준비생의 막 블로그

0개의 댓글