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

≯℡__Kan透↙ 提交于 2019-12-08 11:48:39

问题


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();
    }

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.


回答1:


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



来源:https://stackoverflow.com/questions/5160939/how-to-call-servlet-or-web-service-from-jsf-backing-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!