BackEnd๐Ÿงต

TIL - Servlet

hae02y 2023. 7. 17. 20:53
๋ฐ˜์‘ํ˜•

ํ”„๋กœ์ ํŠธ ์„ธํŒ…

์Šคํ”„๋ง๋ถ€ํŠธ์—์„œ ํŒจํ‚ค์ง• ์„ ํƒ์‹œ์— Jar์™€ War๊ฐ€ ์žˆ๋‹ค. 

 

JAR( JAVA Archive)

.jar ํ™•์žฅ์ž ํŒŒ์ผ์€ Class์™€ ๋ฆฌ์†Œ์Šค ์†์„ฑํŒŒ์ผ, ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ฐ ์•ก์„ธ์„œ๋ฆฌ ํŒŒ์ผ์ด ํฌํ•จ๋˜์–ด์žˆ๋‹ค. ์ฆ‰ ์ž๋ฐ” ํ”„๋กœ์ ํŠธ๋ฅผ ์••์ถ•ํ•œ ํŒŒ์ผ๋กœ ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. JRE๋งŒ์œผ๋กœ๋„ ์‹คํ–‰์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

 

WAR(Web application Archive)

.War ํŒŒ์ผ์€ servlet/ jsp ์ปจํ…Œ์ด๋„ˆ์— ์‚ฌ์šฉํ• ์ˆ˜์žˆ๋Š” ์›น์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ์••์ถ•ํŒŒ์ผ ํฌ๋งท์ด๋‹ค. ์ด๋Š” ์›น๊ด€๋ จ ์ž์›๋งŒ ํฌํ•จํ•˜๊ณ  ์žˆ๊ณ , ์‚ฌ์šฉ์‹œ์— ์›น์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ์‰ฝ๊ฒŒ ๋ฐฐํฌํ•˜๊ณ  ์‚ฌ์šฉํ• ์ˆ˜์žˆ๋‹ค. ๋‹จ์ ์€ WARํŒŒ์ผ์„ ์‹คํ–‰ํ•˜๋ ค๋ฉด Tomcat, Weblogic, Websphere๋“ฑ์˜ Web Server ๋˜๋Š” WAS๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

 

ํ˜„์žฌ ์ƒํ™ฉ์—์„œ๋Š” JSP๊ณต๋ถ€๋„ ํ•„์š”ํ•˜๋ฏ€๋กœ WAR๋ฅผ ์„ ํƒํ•œ๋‹ค.

 

์„œ๋ธ”๋ฆฟ์„ ์‚ฌ์šฉํ• ๋•Œ ํ†ฐ์บฃ๊ฐ™์€ WAS์„œ๋ฒ„๋ฅผ ์ง์ ‘ ์„ค์น˜ํ•˜๊ณ , ๊ทธ์œ„์— ์„œ๋ธ”๋ฆฟ ์ฝ”๋“œ๋ฅผ ํด๋ž˜์Šค ํŒŒ์ผ๋กœ ๋นŒ๋“œํ•ด์„œ ์˜ฌ๋ฆฌ๊ณ  ํ†ฐ์บฃ์„ ์‹คํ–‰ํ•˜๋Š” ๊ณผ์ •์„ ๊ฑฐ์น˜๋Š”๋ฐ ์ด๋ถ€๋ถ„์€ ์ƒ๋žตํ•˜๊ณ  ์Šคํ”„๋ง๋ถ€ํŠธ๋ฅผ ํ†ตํ•ด ๋‚ด์žฅํ†ฐ์บฃ์„ ์‚ฌ์šฉํ•ด๋ณธ๋‹ค.

 

์ฝ”๋“œ

@ServletComponentScan //spring์—์„œ ์ž๋™์œผ๋กœ ์„œ๋ธ”๋ฆฟ์„ ์ฐพ์•„์„œ ๋“ฑ๋ก
@SpringBootApplication
public class ServletApplication {
	public static void main(String[] args) {
		SpringApplication.run(ServletApplication.class, args);
	}
}

@ServletComponentScan์„ ์ž‘์„ฑํ•ด์„œ ์„œ๋ธ”๋ฆฟ์„ ๋“ฑ๋ก

 

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 java.io.IOException;

@WebServlet(name = "requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHeaderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    //์š”๊ธฐ์— ๊ตฌํ˜„
    }
}

request์™€ response๋ฅผ ํ†ตํ•ด ์กฐ์ž‘์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

์œ„๊ทธ๋ฆผ๊ณผ ๊ฐ™์€ ํ˜•ํƒœ๋กœ ์„œ๋ธ”๋ฆฟ์ด ์ƒ์„ฑ๋œ๋‹ค. ์ด๋•Œ ์„œ๋ธ”๋ฆฟ์€ ์š”์ฒญ์ด ์—ฌ๋Ÿฌ๊ฐœ ์žˆ๋”๋ผ๋„ 1๊ฐœ๋งŒ ์ƒ์„ฑ๋œ๋‹ค.

 

๊ฒฐ๋ก 

์„œ๋ธ”๋ฆฟ์œผ๋กœ๋งŒ ์›น์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ๊ตฌํ˜„ํ•ด๋ณด๋‹ˆ ์ž๋ฐ”์ฝ”๋“œ์ƒ์— html์ฝ”๋“œ๊ฐ€ ์„ž์ด๊ฒŒ ๋œ๋‹ค. ์ด๊ฒŒ ์–ผ๋งˆ๋‚˜ ๋ถˆํŽธํ•œ์ •๋„๋ƒ๋ฉด 

w.write("<!DOCTYPE html>\n" +
 "<html>\n" +
 "<head>\n" +
 " <meta charset=\"UTF-8\">\n" +
 " <title>Title</title>\n" +
 "</head>\n" +
 "<body>\n" +
  ...
 "</body>\n" +
 "</html>\n");

์ด๋Ÿฐ์‹์œผ๋กœ ์ž๋ฐ” ์ฝ”๋“œ์— ์ง์ ‘ + ๋ฅผ ํ•ด๊ฐ€๋ฉด์„œ html ์ฝ”๋“œ๋ฅผ ๋‹ค ์ž…๋ ฅํ•ด์ค˜์•ผ๋œ๋‹ค...!

๋ฐ˜์‘ํ˜•