开发者

How to call servlet or web service from JSF backing bean?

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 endDat开发者_JAVA技巧eString = 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();
    }

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.


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:

  • How to use java.net.URLConnection to fire and handle HTTP requests?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜