Wrapper, Filter and Servlet

☆樱花仙子☆ 提交于 2019-12-18 13:29:12

问题


since I am new to Servlet programming, it is possible that I ask a basic question.

I am writing an application where a Filter gets the response from a servlet, and does some computation with it. I found out that I need a wrapper class to catch the response.

My question now is why the wrapper is needed? Thanks in advance!


回答1:


1) Lets first understand how Request and Request Filter work:

When, lets say client, makes a request to servlet, it goes through container. Container decides what servlet Request needs to be forwarded to. Which means, container is in total control.

Container control makes implementing request filter easy because we can just let container know that the Request should go to filter first and then to servlet. Because container is in total control. So implementing request filter is easy.

2) Now lets understand how Response and Response Filter work:

When container invokes Servlet service methods, it passes 2 objects to the methods, Request and Response.

This simply means that Servlet is in total control to send the response back to client. How ?

Because Response object has the pointer to Output Stream Writer object. Which means, once Servlet finishes processing the request, it will straight write the Response back to the client using pointer to Output Writer Stream object. So, Servlet won't wait for anyone (middle men like filter) and straight serve the client. By the time, it will be too late to intervene.

So, what's the solutions ?

Wrapper is our solution.

How Wrapper works ?

So, before container passes the real Request and Response objects to Servlet, we will wrap our Response object and then send the Real Request and Wrapped Response objects to the Servlet service methods.

So now, Servlet has pointer to our Wrapped Output Stream Writer object and not the Real Response Output Stream Writer object. So, when Servlet finishes the request, it will write the response to our Wrapped Stream and then Our Wrapped Response Object will write back to Real Response Writer Stream.

Moral of the story: Use wrapper when dealing with Response. Request doesn't need wrapper concept.



来源:https://stackoverflow.com/questions/16480321/wrapper-filter-and-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!