且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从由嵌入在 JSF webapp 中的小程序调用的 servlet 访问 JSF 会话范围的 bean

更新时间:2023-12-04 16:56:46

如果返回null,那么只能说明两件事:

If it returns null, then it can only mean 2 things:

  1. JSF 尚未事先创建该 bean.
  2. applet-servlet 交互不使用与 web 应用程序相同的 HTTP 会话.

鉴于您描述功能需求的方式,我认为是后者.您需要确保传递 webapp 的会话标识符以及来自小程序的 HTTP 请求.这可以采用 JSESSIONID cookie 或 jsessionid URL 路径属性的形式.

Given the way how you described the functional requirement, I think it's the latter. You need to ensure that you pass the session identifier of the webapp along with the HTTP request from the applet as well. This can be in the form of the JSESSIONID cookie or the jsessionid URL path attribute.

首先,您需要告诉小程序 Web 应用程序正在使用的会话 ID.您可以通过将参数传递给 标签来实现此小程序

First, you need to tell the applet about the session ID the webapp is using. You can do it by passing a parameter to <applet> or <object> tag holding the applet

<param name="sessionId" value="#{session.id}" />

(#{session} 是一个隐式的 JSF EL 变量,引用当前的 HttpSession 又具有 getId() 方法;您不需要要为此创建一个托管 bean,上面的代码行按原样完成)

(the #{session} is an implicit JSF EL variable referring the current HttpSession which in turn has a getId() method; you don't need to create a managed bean for that or so, the above line of code is complete as-is)

可以在小程序中检索如下:

which can be retrieved in the applet as follows:

String sessionId = getParameter("sessionId");

您没有描述如何与 servlet 交互,但假设您使用的是 标准Java SE URLConnection ,指向@WebServlet("/servleturl")servlet,那么你可以使用 setRequestProperty() 来设置请求头:

You didn't describe how you're interacting with the servlet, but assuming that you're using the standard Java SE URLConnection for this, pointing to the @WebServlet("/servleturl") servlet, then you can use setRequestProperty() to set a request header:

URL servlet = new URL(getCodeBase(), "servleturl");
URLConnection connection = servlet.openConnection();
connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
// ...

或者,您也可以将其作为 URL 路径属性传递:

Alternatively, you can also pass it as a URL path attribute:

URL servlet = new URL(getCodeBase(), "servleturl;jsessionid=" + sessionId);
URLConnection connection = servlet.openConnection();
// ...

(请注意,在这两种情况下,案例都很重要)

无论哪种方式,applet-servlet 交互都将在与 JSF 托管 bean 相同的 HTTP 会话中进行.

Either way, this way the applet-servlet interaction will take place in the same HTTP session as JSF managed beans.