Spring Boot Servlet

남영민·2021년 3월 6일
0

SpringBoot

목록 보기
1/4

개발자로의 첫 발을 내딛으며 Spring Boot로 시작하여 꾸준히 글을 쓰고자 합니다...

Java Programming 입문 도서를 열흘만에 1회 정독하고, 업무에 필요한 Spring Boot 시작하였습니다. 웹에 간단하게나마 코딩하는 내용이 반영되니 흥미로웠습니다.

첫 번째 내용은 Spring Boot Servlet입니다.

서블릿은 JVM 기반에서 웹 개발을 하기위한 명세이자 API이다.
서블릿은 HTTP 요청과 응답을 처리하기 위한 내용들을 담고있다.

  1. 서블릿 설정
  • Gradle을 사용하여 서블릿 개발 환경 설정
    -> 자바에서 라이브러리를 편리하게 추가할 수 있는 도구(의존성 관리)
    -> build.gradle 파일을 생성하여 사용
  1. init 메서드로 초기화
public void init(ServletConfig servletConfig) throws ServletException {
    System.out.println("init call");
    this.myParam = servletConfig.getInitParameter("siteName");
    System.out.println("입력받은 사이트 명은" + myParam + "입니다.");
    }
  1. doGet 메서드를 이용하여 GET 메서드 방식의 요청을 응답받음
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
  1. doPost 메서드로 POST 요청에 대하여 처리
 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {}
  1. 멀티파트로 바이너리 데이터 전송
@WebServlet(urlPatterns = "/upload", name = "uploadServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, //2mb
        maxFileSize = 1024 * 1024 * 10, // 10mb
        maxRequestSize = 1024 * 1024 * 50, //50mb
        location = "c:/upload" //파일 저장 위치
)
  1. 필터로 요청에 대하여 전처리 작업
@webFilter("*.jsp")
public class FilterEx implements Filter {
    @Override
    public void init(FilterCofig filterConfig) throws SevletException)
    }
    
    @Override 
    public void doFilter(servletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {}
  1. 쿠키는 사용자가 사이트를 방문했을 때, 사용자의 컴퓨터에 저장되는 정보
Cookie jcookie = new Cookie(name, value);
  1. 세션은 서버와 클라이언트의 유효한 커넥션을 식별하는 정보
@WebServlet(urlPatterns = "/createse")
public class CreateSessionValueServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<html><head><title>세션</title></head><body>");

        HttpSession session = req.getSession();
        session.setAttribute("jpub", "book");
        out.println("세션이 생성되었습니다.");
        out.println("<a href='/readse'>세션 읽기</a></body></html>");
    }
}
  1. 디자인 패턴 활용

내용 출처 : 윤석진. (2018). 스프링 부트로 배우는 자바 웹 개발. 주식회사 제이펍

profile
성장하는 개발자

0개의 댓글