0

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.

Drew H
  • 4,629
  • 9
  • 55
  • 88

1 Answers1

3

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:


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

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Thank you again BaluC(when are you writing a book?). In this case I'm passing a servlet parameters so it can create an Excel spreadsheet for the user to download. – Drew H Mar 01 '11 at 22:34
  • Yes, I already guessed that based on the code snippet :) As to the book, well several people have asked me that before. I wouldn't know where to start. There are already many good books around. Just keep posting questions on SO :) – BalusC Mar 01 '11 at 22:37