如何从 JSF 支持 bean 调用 servlet 或 Web 服务?
我真的找不到正确的方法来做到这一点。
我有这个方法并且它有效,但这似乎是一种解决方法来完成如此基本的事情。
FacesContext context = FacesContext.getCurrentInstance();
String baseURL = context.getExternalContext().getRequestContextPath();
String startDateString = sdf.format(startDate);
String endDateString = sdf.format(endDate);
String url = baseURL + "/Excel?pkgLineId="+selectedPkgLine.getPkgLineId()+"&dateStart=" + startDateString + "&dateEnd=" + endDateString;
try {
String encodeURL = context.getExternalContext().encodeResourceURL(url);
context.getExternalContext().redirect(encodeURL);
} catch (Exception e) {
} finally {
context.responseComplete();
}
我还了解到,调用 servlet 不被认为是最佳实践。如果我将 servlet 移至 Web 服务会怎样?我该如何称呼它?感谢您的任何帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你并不是真的在打电话给他们。您正在将响应重定向给他们。您基本上是在告诉网络浏览器它应该在给定的 URL 上触发新的 HTTP 请求。这是否是最佳实践取决于唯一的功能需求。据给定的代码示例提示,这对我来说似乎完全合法。尽管我可能会使用普通的 HTML
如果您实际上想要以编程方式调用它并处理其响应,那么您应该使用 HTTP 客户端 API。基本的 Java SE API 为此提供了裸露的 java.net.URLConnection API。如果它是一个 Web 服务,例如 JAX-WS/JAX-RS,那么您应该为此使用 API 提供的客户端。
另请参阅:
java.net.URLConnection
来触发和处理 HTTP 请求?与具体问题无关,当您使用 FacesContext#responseComplete() “http://download.oracle.com/javaee/6/api/javax/faces/context/ExternalContext.html#redirect%28java.lang.String%29” rel="nofollow noreferrer">
ExternalContext#redirect ()
(但是当您从 JSF 下提取HttpServletResponse
并对其调用sendRedirect()
时,这是必要的)。You aren't really calling them. You are redirecting the response to them. You are basically telling the webbrowser that it should fire a new HTTP request on the given URL. Whether that is the best practice or not depends on the sole functional requirement. As far the given code example hints, it seems perfectly legal to me. Although I would probably have used a normal HTML
<form action="Excel">
for this instead of a<h:form>
with a managed bean. Again, that depends on the functional requirement (just ask yourself: why exactly do you need JSF for this particular one? Validation? Specific postprocessing?).If you actually want to call it and process its response programmatically, then you should be using a HTTP client API. The basic Java SE API offers the bare
java.net.URLConnection
API for this. If it is a Webservice, for example JAX-WS/JAX-RS, then you should use the API-provided client for this.See also:
java.net.URLConnection
to fire and handle HTTP requests?Unrelated to the concrete problem, manually calling
FacesContext#responseComplete()
is unnecessary when you useExternalContext#redirect()
(but it is necessary when you haul theHttpServletResponse
from under the JSF covers and callsendRedirect()
on it).