-
Servlet 출력 형식의 이해프로그래밍 공부/Servlet과 JSP 2021. 5. 31. 10:53
res.setCharacterEncoding("UTF-8"); res.setContentType("text/html; charset=UTF-8");
뉴렉처 강사님의 동영상 강의를 정리한 글입니다.
@WebServlet("/hi") public class Nana extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); for(int i=0;i<100;i++) { out.println((i+1)+": Hello!!<br>"); } } }
이 예제를 실행해보면
다음과 같이 실행된다. 이것은 서블릿 코드를 통해 전달받은 response 객체를 text로 읽어왔기 때문인데,
이와 같이 브라우저에 컨텐츠 형식을 알려주지 않은 경우 브라우저가 자의적인 해석을 하여 읽어올 수 있다.
따라서 content의 형식을 설정하고 넘겨주어야 한다.
response 객체에 컨텐츠 형식을 지정해보자.
우선 html 파일임을 알려주는 text/html을 추가하고, 인코딩방식과 디코딩 방식을 UTF-8방식으로 일치시킨다.
res.setCharacterEncoding("UTF-8"); res.setContentType("text/html; charset=UTF-8");
이러한 형식을 가진 객체를 브라우저가 읽을 때는 html로, UTF-8로 디코딩하여 읽게 된다.
'프로그래밍 공부 > Servlet과 JSP' 카테고리의 다른 글
사용자 입력 받기 - 직접 입력 (0) 2021.05.31 사용자 입력 받기 - GET 요청과 쿼리 스트링 (0) 2021.05.31 Annotation을 이용하여 서블릿 매핑하기 (0) 2021.05.31 이클립스를 이용한 서블릿 프로그래밍(xml 파일을 이용한 서블릿 매핑) (0) 2021.05.31 Servlet 프로그램 만들기 (0) 2021.05.18