【问题标题】:How to reach HTTP Request in Java class [duplicate]如何在 Java 类中访问 HTTP 请求 [重复]
【发布时间】:2019-09-06 08:16:37
【问题描述】:

我想在我编写的拦截器中查看对网页的请求。我将根据传入请求中的一些值更改我的响应值。我将使用类似的东西;

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

这是我的 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>

这是我的 TestInterceptor.java 类的一部分;

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;
}

使用该功能的解决方案或其他方式是什么。 感谢您的帮助。 注意:我使用的是 Struts 框架

【问题讨论】:

  • FWIW:这类问题几乎总是可以通过一点点研究自行回答。花几分钟学习 Javadocs 会找到答案。
  • 我同样厌倦了那些不遵循 Javadocs(点击 2-4 次即可获得答案)或破解打开现有拦截器只是 look 的人在它。事情是这样的:您可以通过跟踪文档和代码来解决它。这几乎是每个开发人员都需要的三项技能之一:跟踪能力。 (另外两个是正则表达式和递归。)
  • 此外,除了忽略阅读 Javadocs 和/或代码时的尽职调查之外,在网络上搜索“struts 2 拦截器访问请求标头”会导致多个答案,包括 SO,这使得问题成为反正都是骗人的。所以每个开发者都需要四项技能,加上“搜索网络”。
  • 你完全正确 :)) 步行上班
  • 为我骑自行车 ;) 请不要对我的 cmets 做出负面解释——它们是为了帮助,而不是伤害。我还将更新一些 S2 文档,以更直接、更清晰地包含这些信息。

标签: java struts2 interceptor struts2-interceptors


【解决方案1】:

你可以从 ActionContext 中得到它

ActionContext context = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);

【讨论】:

    【解决方案2】:

    您需要在请求 HTTP 被触发之前修改您的请求(例如,在执行 Action 之前和在执行 Result 之前)。

    PreResultListener 允许我们这样做。您的TestInterceptor 应该实现PreResultListener 并提供beforeResult() 方法的实现。在此方法中,我们从ActionContext 中获取HttpServletResponse 对象,并为其添加自定义逻辑。

    对于您的情况:修改标头值

    TestInterceptor在before方法中注册自己的ActionInvocation,在结果执行前得到回调。

    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);  
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 2010-11-24
      • 2021-08-04
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多