Servlet 기초

서블릿 매핑주소 연결

  • get방식일때는 doget이 호출, post방식일때는 dopost가 호출됨 => 근데 어차피 doGet만 호출되긴함
  • @WebServlet(“/start”) 에서 start부분은 변경 가능함
  • 대신 jsp에서 호출할때는 “../start” 로 보내줘야 서블릿 실행됨
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

  </head>
  <body>

    <h2>서블릿 매핑주소 지정하기</h2>

    <a href="../start">예제1 - 기본 라이프사이클 확인하기 예제</a><br>

  </body>
</html>

package servlet.day0514;

import java.io.IOException;
import javax.servlet.ServletConfig;
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 Ex1ServeltTest
*/

//기본적으로는 클래스 이름과 같으나 변경도 가능하다.
@WebServlet("/start")
public class Ex1ServeltTest extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
	     * @see HttpServlet#HttpServlet()
	     */
  public Ex1ServeltTest() {
    super();
    // TODO Auto-generated constructor stub
    System.out.println("처음만드는서블렛!! 생성자입니다 ");
  }

  /**
		 * @see Servlet#init(ServletConfig)
		 */
  public void init(ServletConfig config) throws ServletException {
    // TODO Auto-generated method stub
    System.out.println("처음만드는서블렛!! 이니트메서드호출 ");

  }

  /**
		 * @see Servlet#destroy()
		 */
  public void destroy() {
    // TODO Auto-generated method stub
    System.out.println("처음만드는서블렛!! 디스트로이메서드 호출~");

  }

  /**
		 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
		 */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("두겟두겟");

    //브라우저에 출력할 내용 (직접쓰는건 굉장히 불편하다..)
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
		 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
		 */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("두포스트~");
    doGet(request, response);
  }
}
  • doGet 메서드로 출력해보기
package servlet.day0514;

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 Ex2ServeltWrite
	 */
//@WebServlet("/hello.do")

//일반적으로는 매핑주소는 보통 하나만 지정하는데, 만약 여러개의 매핑주소를 주소 싶다면...
//name: 서블렛 별칭, urlPatterns 또는 value에 여러개의 매핑 주소를 지정할 수 있다.
@WebServlet(name="board",value= {"/hello.do","/board/list.do","/guest/list.do"})
public class Ex2ServeltWrite extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
	     * @see HttpServlet#HttpServlet()
	     */
  public Ex2ServeltWrite() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
		 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
		 */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //		response.getWriter().append("Served at: ").append(request.getContextPath());
    //보통은 여기서 출력은 안함... 그냥 연습이다. 아래는 한글을안깨지게 하기위한 명령어들 
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.write("have a nice day!!<br>");
    out.write("안녕하세요?"); //한글은 깨진다.
  }

  /**
		 * @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);
  }
}
package servlet.day0514;

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

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 Ex3ServletInclude
	 */
@WebServlet("/Ex3")
public class Ex3ServletInclude extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.write("including jsp file on servlet!!!<br>"); //이걸 쓰려면 한영 관계없이 위에 세줄을 꼭 넣어줘야 jsp로 인식이 된다.
    //request에 데이타를 저장 x
    request.setAttribute("name", "alice");
    request.setAttribute("hp", "010-111-2222");
    request.setAttribute("addr", "seoul");
    //jsp파일 인클루드 하기 
    //include & forward 는 request 와 response가 그대로 전달됨. url 주소는 안바뀜~~
    RequestDispatcher rd = request.getRequestDispatcher("day0514_servlet/Ex3_result.jsp");
    // rd.include(request, response); 
    // include는 += 이라면 forward는 = 같은 개념이라 다 지워진다.
    rd.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);
  }

}

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

  </head>
  <body>
    This is Ex3 result.jsp
    <pre>
	${name} 
	${hp }
	${addr }

	</pre>
  </body>
</html>

Categories:

Updated:

Comments