Sunday, January 11, 2009

Read Request Body in Filter

Is it possible to intercept HTTP Request in order to read HTTP Request Body (HTTP Request Payload) before it is served by target servlet or JSP?

The answer is yes. You can use Servlet Filter to read, "filter" or modify ServletRequest (HTTPServletRequest) object before the request object is sent to and serve by the final servlet.

What if I read a request body within a servlet filter, is the body still going to be available to be read again by the servlet, or can it be read only once?

Yes, but it is a little bit tricky.
Because of the fact that the request body can be read only once. If you read the body in a filter, the target servlet will not be able to re-read it and this will also cause IllegalStateException. You will need ServletRequestWrapper or its child: HttpServletRequestWrapper so that you can read HTTP request body and then the servlet can still read it later.

public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}

@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}

@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}

public String getBody() {
return this.body;
}
}

The first step is to create a class that extends HttpServletRequestWrapper. Then, use the constructor to read HTTP Request body and store it in "body" variable. The final step is to override getInputStream() and getReader() so that the final servlet can read HTTP Request Body without causing IllegalStateException.

Here's how to use RequestWrapper in the filter.

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

Throwable problem = null;

MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) request);

String body = myRequestWrapper.getBody();
String clientIP = myRequestWrapper.getRemoteHost();
int clientPort = request.getRemotePort();
String uri = myRequestWrapper.getRequestURI();

System.out.println(body);
System.out.println(clientIP);
System.out.println(clientPort);
System.out.println(uri);

chain.doFilter(myRequestWrapper, response);
}

86 comments:

  1. Thank you for the code sample, I have been trying to do this myself. However, after adding the filter the downstream servlet loses all its http post parameters. The parameters re-appear only after the above filter is removed. Running OpenJDK 6 with Tomcat 6.0.16

    ReplyDelete
  2. There is a problem with this code...
    When I use POST request to submit my data and try to read some parameter with myRequestWrapper.getParameter("paramName") I get null. I suppose this wrapper should implement its own getParameter(String) method...

    ReplyDelete
  3. In actuality, the code above will not work if the call is made to the InputStream, and later you request any parameter. You must override all of the parameter methods for this to work.

    ReplyDelete
  4. We use this code and found it very useful.
    but we found a bug- when reading the body from the input stream, you use the default charset of the machine:
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    instead, you should probably use the request body charset.
    so you should change the above line to this line:
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream, request.getCharacterEncoding()));

    ReplyDelete
  5. Thanks sir, but how can I get the request body from another class? I have a class that makes the md5 digest of that request body.

    Thanks a lot in advance.

    ReplyDelete
  6. Very good post. PRECISELY what I needed to know!

    ReplyDelete
  7. Under which class is the doFilter() Method? Do I insert it in the servlet class?

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thanks for the awesome work. I was wrong doubting your code. (THUMBS UP)

    ReplyDelete
  12. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  13. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    python training in chennai
    python course in chennai
    python training in bangalore

    ReplyDelete
  14. The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.
    AWS Training in pune
    AWS Online Training

    ReplyDelete
  15. I am amzaed by the way you have explained things in this post. This post is quite interesting and i am looking forward to read more of your posts.
    redmi note service center in chennai
    redmi service center in velachery
    redmi service center in t nagar
    redmi service center in vadapalani

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. does not work the code above even with the refactorization

    ReplyDelete
  18. සතුටින් හා ප්රීතිමත් දවසක්. ලිපිය හුවමාරු කර ගැනීම සඳහා ඔබට ස්තූතියි

    máy phun tinh dầu

    máy khuếch tán tinh dầu tphcm

    máy khuếch tán tinh dầu hà nội

    máy xông phòng ngủ

    ReplyDelete
  19. Thanks for sharing it.I got Very significant data from your blog.your post is actually Informatve .I'm happy with the data that you provide.thanks


    click here
    see more
    visit us
    website
    more details





    ReplyDelete
  20. Thanks for your excellent blog and giving great kind of information. So useful. Nice work keep it up thanks for sharing the knowledge.
    Visit us
    Click Here
    For More Details
    Visit Website
    See More

    ReplyDelete
  21. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve.I’m satisfied with the information that you provide for me.

    aws course
    aws certification
    aws devlopment
    aws syllabus

    ReplyDelete
  22. May I simply say what a relief to find someone who genuinely knows what they're discussing on the net. You definitely realize how to bring a problem to light and make it important. More people should read this and understand this side of the story. I was surprised you are not more popular since you surely have the gift.
    Tech news

    ReplyDelete
  23. Everything is very open with a clear explanation of the issues. It was definitely informative. Your site is very helpful. Many thanks for sharing!
    Gadgets

    ReplyDelete
  24. Thanks for sharing such a great information..Its really nice and informative..

    aws tutorial for beginners
    aws videos

    ReplyDelete
  25. You're so awesome! I don't believe I have read a single thing like this before. So nice to find someone with a few genuine thoughts on this subject. Really.. thank you for starting this up. This website guide is one thing that is required on the web, someone with some originality!

    ReplyDelete
  26. It's really a nice and useful piece of information about AWS. I'm satisfied that you shared this helpful information with us.Please keep us informed like this. Thank you for sharing.


    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  27. You've made some good points there. I looked on the internet for additional technology information about the issue and found most people will go along with your views on this website.

    ReplyDelete
  28. I really enjoyed your blog Thanks for sharing such an informative post.

    digital marketing coaching in hubli

    ReplyDelete
  29. Thanks for sharing great info … Hiring a limousine are excellent option to make your special occasion more delightful. Limo Hire Melbourne.Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  30. Thank you for your informative article, I have been doing research on this subject, and for three days I keep entering sites that are supposed to have what I am searching for, only to be discouraged with the lack of what I needed. Thank you again.
    DevOps Training in Chennai

    DevOps Online Training in Chennai

    DevOps Training in Bangalore

    DevOps Training in Hyderabad

    DevOps Training in Coimbatore

    DevOps Training

    DevOps Online Training

    ReplyDelete
  31. This is a great inspiring website. I am pretty much pleased with your good work. Thousands of people like me visit here every day and get useful information from here.keep it up!!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  32. That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.
    acte reviews

    acte velachery reviews

    acte tambaram reviews

    acte anna nagar reviews

    acte porur reviews

    acte omr reviews

    acte chennai reviews

    acte student reviews

    ReplyDelete
  33. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    https://www.3ritechnologies.com/course/mean-stack-training-in-pune/

    ReplyDelete
  34. Good Post! it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Looking for the best PPC course in Bangalore India? Learn PPC from Ranjan Jena, 10+ Years Expert Google Ads Trainer. 1000+ Students Trained @ eMarket Education, Koramangala, Bangalore.
    Best Online Digital Marketing Courses in Bangalore, India
    Best Digital Marketing Institute in Bangalore

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Very interesting article to read it. I would like to thank you for the efforts you had made for writing this wonderful article. This article inspired me to read more. Keep sharing on updated posts…

    Learn Digital Marketing Course in Bangalore with Live Project Work & Case Studies taught by Ranjan Jena (10Yrs Trainer). 100% Guarantee to Clear Job Interview.

    ReplyDelete
  37. Saham perusahaan diterbitkan di atas kertas, memungkinkan investor untuk memperdagangkan saham bolak-balik dengan investor lain, tetapi bursa yang diatur tidak ada sampai pembentukan Bursa Efek London (LSE) pada tahun 1773. Meskipun sejumlah besar gejolak keuangan mengikuti pendirian segera dari LSE, perdagangan pertukaran secara keseluruhan berhasil bertahan dan berkembang sepanjang tahun 1800-an. cek juga markets dan Buku Investasi Saham Terbaik

    ReplyDelete
  38. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers.thanks for sharing it and do share more posts like this.


    IT Training in Pune with placements

    IT Training in Pune

    ReplyDelete
  39. Xanax belongs to the benzodiazepines drug, which is using to address anxiety, panic disorder, and stress by stimulating the disturbed and unbalanced chemicals in the brain. Xanax offers calming effects in the brain to enhance the productivity evaluator's consultation and guidelines. Buy Xanax online

    buy xanax online

    ReplyDelete
  40. Oxycontin may be a brand of Oxycodone, this is often the controlled-release Oxycodone tablets, intended to be taken every 12 hours. Oxycodone may be a semi-synthetic opioid synthesized from thebaine, an opioid alkaloid found in the Persian poppy, and one among the various alkaloids found within the Papaver somniferous. buy oxycontin online

    buy oxycodone online

    ReplyDelete
  41. Adderall Online is being used under the observation of health experts to address ADHD and narcolepsy without causing any future health issues. Therefore, it works to promote a healthy and progressive mindset by reducing the impact of aggression, stress, and anger. and the formula of Adderall is C9H13N.buy Adderall online

    buy adderall online

    ReplyDelete
  42. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Primavera P6 Certification Training in Chennai | Primavera Training in India

    ReplyDelete
  43. The best quality hair extensions are available to clients directly. If only you could feel how SILKY this hair is and will continue to be for over a year. This hair is worth the investment and will give you stress-free beautiful hair. The hand-tied weft is ideal for thin hair because it is extremely flat.

    ReplyDelete
  44. https://www.facebook.com/Jack-russell-puppies-looking-for-a-lovely-home-103472108733880/

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. Amazing write-up! Really Good.
    Now the foundation of any business is digital marketing. Adsify marketing is the best Digital marketing in Trivandrum.

    ReplyDelete
  47. preparation they can also download notes from our website. We have Completely Organized, Well Researched, Qualitative Mppsc Notes. We also provide Sharma Academy Book Reader App with our MPPSC Study notes package.

    ReplyDelete
  48. Superb article, I really appreciate your work on this website. It is a very helpful website. Do you know about the Turkey visa free country ? Here is a complete list of those countries which do not require a visa to visit Turkey. With Just one click you can easily check the name of your country which is included or not in the list of those countries which do not require a visa to enter Turkey.

    ReplyDelete
  49. wordpress design services agency Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today!

    ReplyDelete