muneebShabbir
muneebShabbir

Reputation: 2528

Setting Request Header in java

Is there any way to modify or set-header of request inside action class? I want to modify it or you can say i want to put flag inside request Header just like we put values in 'attribute' and parameters.

Upvotes: 0

Views: 8077

Answers (7)

Dipin Narayanan
Dipin Narayanan

Reputation: 1105

If you are trying to open a URL connection using Java, you can something like this What is the proper way of setting headers in a URLConnection?

If you can make requests with a browser, You can use this Firefox plugin to add/modify any number of request headers.

https://addons.mozilla.org/en-US/firefox/addon/modify-headers/

Good Luck

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160171

The answer to this depends on what problem you're trying to solve.

One of your comments suggests you're trying to test; if this is the case you have two basic options:

  1. Use a mock request (unit-style testing).
  2. Change the header from the client (integration-style testing).

For testing from real clients, set headers on the client side.

For mocking client interactions, you should be using some form of mock. StrutsTestCase, for example, provides MockStrutsTestCase (outside container) and CactusStrutsTestCase (inside container) classes allowing easy manipulation of request properties and characteristics.

Upvotes: 1

MahdeTo
MahdeTo

Reputation: 11184

I think they only clean way you can do this is via an HttpServletRequestWrapper

Just override getHeader, getHeaders, getHeaderNames and you are good to go.

Upvotes: 0

Juha Laiho
Juha Laiho

Reputation: 596

I think you'd need to wrap the original request into a request class containing the change you wish to have.

It might be better design to have the request parameters parsed earlier in processing to such objects that make more sense to your application logic, and then set the state of those objects in the place where you now would like to modify the original header.

Upvotes: 1

Artem
Artem

Reputation: 4397

You can do this using HttpServletRequestWrapper. But it's quite dirty solution. Are there really no other ways to solve your problem?

Upvotes: 3

drekka
drekka

Reputation: 21883

You need to give more details. It sounds like you want to manipulate the request header once the server has received the request. I'm not sure I understand why you would want to do that. Modifying the response headers make sense. But not the request.

Upvotes: 0

Buhake Sindi
Buhake Sindi

Reputation: 89169

You cannot. Request parameters returned from the servlet are unmodifiable Map. You cannot add/delete content returned from request (via servlet).

In order to set a flag, my suggestion is to store it in a session, and on another action, retrieve the flag & delete it from session.

Upvotes: 1

Related Questions