JSP / Servlet设计问题 - 通过JNDI全局提供请求/响应 [英] JSP/Servlet design question - Make request/response globally available via JNDI

查看:131
本文介绍了JSP / Servlet设计问题 - 通过JNDI全局提供请求/响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,总是能够从代码的任何部分访问当前请求或响应。这个概念是PHP编程的基础。 请求数据,响应数据,会话数据(等)总是在那里

In PHP one is always able to access the current request or response from any part of their code. This concept is fundamental to PHP programming. Request data, response data, session data (etc) are always there!

这在Java Servlets中不会发生!为了能够访问代码中的HttpServletRequest,HttpServletResponse,HttpSession(等),您需要将它们作为函数变量传递。这意味着您无法对固有地知道所有这些的Web框架进行编码,并消除了传递它们的复杂性。

This does not happen in Java Servlets! In order to have access to the HttpServletRequest, HttpServletResponse, HttpSession (etc) in your code you need to pass them around as function variables. This means that you cannot code a web framework that inherently "knows" about all these and removes the complexity of passing them around.

所以,我已经设计了这个解决方案:

So, I have devised this solution:


  1. 创建anf注册ServletRequestListener。

  2. 在requestInitialized事件绑定之后当前HttpServletRequest到JNI上下文给出了当前Thread的名称(Thread.currentThread()。getName());

  3. 在requestDestroyed事件解除绑定上面的JNI资源后进行清理。

这样,人们就可以从代码的任何地方访问当前的请求/响应,因为他们总是存在于JNI上下文中,可以通过提供当前线程的名称来检索。

This way one has access to the current request/response from any place of their code, since they are always there in the JNI context and can be retrieved by providing the current thread's name.

所有已知的servlet容器为每个请求实现单线程模型,所以没有办法让请求混淆(当然一定不要忘记清理

All known servlet container implement the single-thread model for each request, so there is no way for the requests to get mixed up (of course one must not forget to clean them up).

默认情况下,每个网络应用程序的 JNI资源 分开,因此没有任何问题混淆它们或者是一个可以访问其他人的请求的网络应用程序可能产生的安全问题。

Also the JNI resources of each web application are separated by default so there are no concerns of mixing them up or of security issues that could arise from one web application having access to the requests of the others.

有点扭曲,但又好又简单...

Kinda twisted, but nice and simple...

你怎么看?

推荐答案

我认为有些网络框架( GWT,Axis)已经这样做了,但是以一种更简单的方式:使用 ThreadLocal 静态变量(或可从单例访问)。 Spring也有这种可能性。

I think some web frameworks (GWT, Axis) already do that, but in a much simpler way: by using a ThreadLocal static variable (or accessible from a singleton). Spring also has this possibility.

我不确定它是否适用于所有容器。如果容器使用非阻塞IO并重用相同的线程来并行处理多个请求,则它将不再起作用。

I'm not sure it works with all the containers, though. If the container uses non-blocking IO and reuses the same thread to handle multiple requests in parallel, it won't work anymore.

参见从Java代码获取HttpServletRequest(请求)对象以获取类似问题(及其答案) 。

See Get the HttpServletRequest (request) object from Java code for a similar question (and its answers).

这篇关于JSP / Servlet设计问题 - 通过JNDI全局提供请求/响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆