그날그날메모

서블릿 리디렉션과 전달

Java

서블릿 리디렉션과 전달

그날그날메모 2021. 4. 17. 20:18

1. 개요

때때로 Java Servlet의 초기 HTTP 요청 핸들러가 요청을 다른 리소스에 위임해야합니다. 이 경우 요청을 추가로 전달하거나 다른 리소스로 리디렉션 할 수 있습니다.

두 메커니즘을 모두 사용하고 각각의 차이점과 모범 사례에 대해 논의 할 것입니다.

2. Maven 의존성

먼저 Servlet Maven 의존성을 추가해 보겠습니다.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.0</version>
</dependency>

최신 버전은 여기 에서 찾을 수 있습니다 .

3. 앞으로

이제 바로 들어가서 간단한 진행 방법을 살펴 보겠습니다.

protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    RequestDispatcher dispatcher = getServletContext()
      .getRequestDispatcher("/forwarded");
    dispatcher.forward(req, resp);
}

We get hold of RequestDispatcher reference from parent Servlet and point it to another server resource.

Simply put, this will forward the request.

When a client submits a request to http://localhost:8081/hello?name=Dennis, this logic will run and the request will be forwarded to “/forwarded“.

4. Redirect

Now that we understand the concept of forwarding, let's have a look at a quick snippet for redirecting:

protected void doGet(HttpServletRequest req, HttpServletResponse resp){
    resp.sendRedirect(req.getContextPath() + "/redirected");
}

We use original response object to redirect this request to another URL: “/redirected”.

When a client submits a request to http://localhost:8081/welcome?name=Dennis, the request will be redirected to http://localhost:8081/redirected.

To find out more about doing redirects in the context of Spring, have a look at our dedicated article here.

5. Differences

We passed the parameter “name” with a value in both cases. Simply put, forwarded requests still carry this value, but redirected requests don't.

This is because, with a redirect, the request object is different from the original one. If we still want use this parameter, we need to save it in the HttpSession object.

Here is a list of major differences between servlet forward and redirect:

Forward:

  • The request will be further processed on the server side
  • The client isn't impacted by forward, URL in a browser stays the same
  • Request and response objects will remain the same object after forwarding. Request-scope objects will be still available

Redirect:

  • The request is redirected to a different resource
  • The client will see the URL change after the redirect
  • A new request is created
  • Redirect is normally used within Post/Redirect/Get web development pattern

6. Conclusion

Forwarding and redirecting are both about sending a user to different resources, although they have quite different semantics.

Picking between these is simple. If the previous scope is required, or the user doesn't need to be informed, but the application also wants to perform an internal action then use forwarding.

범위를 삭제하거나 새 콘텐츠가 로그인 페이지로의 리디렉션 또는 양식 제출 완료와 같은 원래 요청과 연결되지 않은 경우 리디렉션을 사용 합니다.

항상 그렇듯이 예제 코드는 GitHub 에서 찾을 수 있습니다 .

참고
  • https://docs.spring.io/spring-framework/docs/current/reference/html
  • https://www.baeldung.com/servlet-redirect-forward