빅데이터 서비스 교육/JSP Servlet

JSP/ Servlet 웹 동작 방식

Manly 2022. 5. 2. 16:14
반응형

@WebServlet("/문자열")     (annotation)

       -> URLMapping (별명)

 Servlet을 동작시키기 위해서 패키지명.클래스명을 써야하는데 너무 길어지니까

Servlet을 동작시키기위해 문자열과 연결시켜주는 URLMapping을 쓴다.

 

각 서블릿마다 고유한 Mapping을 가져야 한다. ( 중복X)

 

 URL

http://localhost:8081/Ser/ex01

 - http://  ->  protocol

 - localhost -> 서버의 ip주소

 - :8081    -> 지정된 포트번호

 - /Ser  ->  Context Path, 컴파일 된 파일이 위치 ,     path는 가변적이고 복사했을때 겹치지 않게 잘 바꿔줘야한다.
                            servers에서 server.xml에서 source context - path를 바꾸면 저장 파일 위치를 바꿀 수 있다

 

 - /ex01 : URLMapping
 - context path, URLMapping 모두 고유값을 가져야 한다. (한 servlet당 하나씩만 가져야한다)

 

 

Servlet을 실행 시키기 위한 메소드

Servlet의 동작 흐름

 request:     요청에 대한 정보를 담고있는 객체
 response:   응답에 대한 정보를 담고있는 객체

 

web Server가 WAS로 요청했을때 requset, response가 동작하고 다시 web Server로 돌아가 클라이언트에게 가면서 소멸한다.

 

 

 

※ 응답 형식 지정(우리가 응답해줄 내용이 어떤 형식인가, 인코딩 방식)

response.setContentType("text/html; charset=utf-8");

 

 

 response 대신에 화면에 출력을 해줄 PrintWriter

PrintWriter out = response.getWriter();

 

out.print();

 

짝꿍이 접속했을때 출력문, 쌤이 접속했을때 출력문

String addr = request.getRemoteAddr();
		System.out.println(addr);
		
		// response: 응답에 대한 정보를 담고있는 객체
		
	System.out.println("접속 성공!");
	//ctrl+f11 ->main메서드
	// 자동으로 요청 -> 크롬열림 -> 주소창에 자동으로 url(요청)
	if(addr.equals("111.10.1.10")) {
		System.out.println("짝꿍접속");
	}else if(addr.equals("111.10.1.11")) {
		System.out.println("쌤 접속");
	}

 

Hello라는 문구를 가진 웹

	private static final long serialVersionUID = 1L;
	// 직렬화
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 실행하는 service 메소드
        // response : 응답정보를 담고있는 객체
		// printWriter : 응답 내용을 작성하는데 필요한 객체
		
		// 1. 응답 형식 지정(우리가 응답해줄 내용이 어떤 형식인가, 인코딩 방식)
		//                      ("문서형식; charset=d 인터넷);
		response.setContentType("text/html; charset=utf-8");
		
		// 2. PrintWriter 객체 생성
		// 출력 스트림
		PrintWriter out = response.getWriter();
		
		// 3. 응답 내용 작성
//		out.print("<html> <head> </head> <body> <h1> Hello </h1> </body> </html>");
		out.print("<html>");
		out.print("<head> </head>");
		out.print("<body>");
		
		out.print("<h1> Hello </h1>");
		
		out.print("</body>");
		out.print("</html>");
		
	}

↓  

 

 

 

Client에게 구구단을 응답하기

        // 1. 응답 형식 지정
		response.setContentType("text/html; charset=utf-8");
		// 2. PrintWriter객체 생성
		PrintWriter out = response.getWriter();
		// 3. out.print로 응답 내용 작성
		out.print("<html>");
		out.print("<head> </head>");
		out.print("<body>");
		out.print("<table border='1'>");
		for (int i = 1; i <=9; i++) {
		out.print("<tr>");
		out.print("<td>"+ "5*"+i+"="+5*i +"</td>");
		out.print("</tr>");	
		}
		out.print("</table>");
		out.print("</body>");
		out.print("</html>");

 

 

 

반응형