How to reach HTTP Request in Java class

549 views Asked by At

I want to see the request to the web page in an Interceptor I wrote. I will change my response value according to some values in the incoming request.I'm gonna use something like that ;

String ex = request.getHeader("GET");
if(ex.contains("addHeader("a","example")"));
     response.setHeader("a","null");

Here is my index.ft:

Your name: <@s.url value="${name}"/>
Enter your name here:<br/>
<form action="" method="get">
<input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>

Here is part of my TestInterceptor.java class;

public class TestInterceptor implements Interceptor {
....
@Override
public String intercept(ActionInvocation ai) throws Exception {
    System.out.println("before");

    //the area where I want to write the codes I want to use above
    // I can't to reach request.getHeader(...) function in here
    String result = ai.invoke();
    System.out.println("after");
    return result;
}

What's the solituon or another way to use that functions. Thanks for helping. Note : I'm using Struts framework

2

There are 2 answers

0
TruckDriver On BEST ANSWER

You can get it from ActionContext

ActionContext context = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
0
Hassam Abdelillah On

You need to modifty your request before the request HTTP is triggerd (e.g before the Action has executed and before the Result is executed).

PreResultListener allows us to do just that. Your TestInterceptor should implement PreResultListener and provides implementation of the beforeResult() method. In this method, we get the HttpServletResponse object from the ActionContext and add custom logic to it.

For your case : modifying header value

The TestInterceptor registers itself with the ActionInvocation in the before method, which gets a callback before the result is executed.

public class TestInterceptor extends AbstractInterceptor implements  PreResultListener {

@Override
public String intercept(ActionInvocation invocation) throws Exception {
  before(invocation);
    return invocation.invoke();
}

private void before(ActionInvocation invocation) {
  invocation.addPreResultListener(this);
}

private void modifyHeader(Object action, HttpServletResponse response) {
  response.addHeader("myHeader", "myValue");
}

public void beforeResult(ActionInvocation invocation, String resultCode) {
  ActionContext ac = invocation.getInvocationContext();
  HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE);
  modifyHeader(invocation.getAction(), response);  
}
}