如何从JSF支持bean调用servlet或Web服务? [英] How to call servlet or web service from JSF backing bean?

查看:98
本文介绍了如何从JSF支持bean调用servlet或Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我严重找不到正确的方法.

I seriously cannot find the correct way to do this.

我有这种方法,它可以工作,但是似乎要做一些基本的事情.

I have this method and it works, but it seems kind of a work around to do something so basic.

  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服务怎么办?我该怎么打电话呢?感谢您的帮助.

I have also read that calling servlets is not considered best practice. What if I moved my servlet to a web service? How would I go about calling that? Thanks for any help.

推荐答案

您并不是真的在称呼他们.您正在将响应重定向到他们.您基本上是在告诉Web浏览器,它应该在给定的URL上触发一个新的HTTP请求.这是否是最佳实践,取决于唯一的功能要求.就给定的代码示例而言,对我来说似乎完全合法.尽管我可能为此使用了普通的HTML <form action="Excel">而不是带有托管bean的<h:form>.同样,这取决于功能要求(问问自己:为什么对这个特定的JSF到底需要JSF?验证还是特定的后处理?).

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?).

如果您实际上 要调用它并以编程方式处理其响应,那么您应该使用HTTP客户端API.基本的Java SE API为此提供了裸露的java.net.URLConnection API.如果它是Web服务,例如JAX-WS/JAX-RS,则应为此使用API​​提供的客户端.

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.

与具体问题无关,使用

Unrelated to the concrete problem, manually calling FacesContext#responseComplete() is unnecessary when you use ExternalContext#redirect() (but it is necessary when you haul the HttpServletResponse from under the JSF covers and call sendRedirect() on it).

这篇关于如何从JSF支持bean调用servlet或Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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