inblog logo
|
harimmon
    스프링부트

    [스프링부트] 10. request객체 3

    백하림's avatar
    백하림
    Mar 19, 2025
    [스프링부트] 10. request객체 3

    DemoServlet: 모든 요청을 처리하는 서블릿 (Front Controller)

    package org.example.demo9; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; // http://localhost:8080/ @WebServlet("/") // 모든 요청이 여기로 몰린다. ex) /, /abc, /a, /b, /c public class DemoServlet extends HttpServlet { // http://localhost:8080?path=a @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // body -> path=값&name=값 // queryString -> ?path=값&name=값 String path = req.getParameter("path"); if (path.equals("a")) { req.setAttribute("name", "ssar"); req.getRequestDispatcher(ViewResolver.viewName("a")).forward(req, resp); } else if (path.equals("b")) { req.setAttribute("age", 20); req.getRequestDispatcher(ViewResolver.viewName("b")).forward(req, resp); } } }

    ViewResolver: JSP 파일 경로를 설정하는 역할

    package org.example.demo9; public class ViewResolver { private static final String prefix = "/WEB-INF/views/"; private static final String suffix = ".jsp"; public static String viewName(String filename) { return prefix + filename + suffix; } }

    a.jsp, b.jsp: View (화면)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>a.jsp</h1> <h3>내 이름은 : ${name}</h3> </body> </html>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>b.jsp</h1> <h3>내 나이는 : ${age}</h3> </body> </html>
    1️⃣ 클라이언트 요청
    • http://localhost:8080?path=a
    • http://localhost:8080?path=b
    2️⃣ DemoServlet이 요청을 처리
    • path=a → name="ssar" 전달 후 a.jsp로 포워딩
    • path=b → age=20 전달 후 b.jsp로 포워딩
    3️⃣ JSP에서 데이터 출력
    • ${name} → "내 이름은 : ssar"
    • ${age} → "내 나이는 : 20"
    폴더 구조 
(WEB-INF 보안 폴더이기 때문에 
아래와 같이 찾으려면 이제는 찾을 수 없다.)
    폴더 구조 (WEB-INF 보안 폴더이기 때문에 아래와 같이 찾으려면 이제는 찾을 수 없다.)

    WEB-INF/views/a.jsp에 위치하면 직접 접근 불가능

    http://localhost:8080/a.jsp
    notion image
    http://localhost:8080/b.jsp
    notion image

    올바른 접근 방식 (Front Controller 사용)

    http://localhost:8080/?path=a
    notion image
    http://localhost:8080/?path=b
    notion image
    💡

    특징

    ✅ Front Controller 패턴
    ✅ ViewResolver 활용 (JSP 경로 자동 설정)
    ✅ request.setAttribute()로 데이터 전달
    ✅ RequestDispatcher.forward()로 JSP 이동
    결론: 서블릿이 요청을 받고, 데이터 바인딩 후 JSP로 포워딩하는 MVC 구조
    Share article

    harimmon

    RSS·Powered by Inblog