Roberto
Roberto

Reputation: 847

How to obtain request headers, remote address and other HttpServletRequest-specific information?

I have a JSF 2.0 web project, my web have a form and it have to do:

  1. Get the parametres of the form and save it in a Bean (Done)

  2. Get this information from the servlet:

    • Remote Address:
    • Remote Host:
    • Locale:
    • Content Type:
    • Boundary:
    • Content Length:
    • Character Encoding:

  3. Insert the Bean data and Servlet data in a table of a database (waiting step 2)

I dont know much about Servlets in JSF, i dont need if i have to make one or not. I only have the code of that but in JSP:

    String informe="";
    Enumeration a = request.getHeaderNames();
    while(a.hasMoreElements() ){
        String h = a.nextElement().toString();
        informe += h+": "+request.getHeader(h)+"\n";
    }
    a = request.getAttributeNames();
    while(a.hasMoreElements() ){
        String h = a.nextElement().toString();
        informe += h+": "+request.getHeader(h)+"\n";
    }
    informe += "Remote Address: "+request.getRemoteAddr()+"\n";
    informe += "Remote Host: "+request.getRemoteHost()+"\n";
    informe += "Locale: "+request.getLocale()+"\n";
    informe += "Content Type: "+request.getContentType()+"\n";
    informe += "Content Length: "+request.getContentLength()+"\n";
            .....
            ..

I don't know how I can get the request information in JSF and wich steps I have to do. I readed a lot of pages but I think that I don't need all things that they do.

Upvotes: 3

Views: 1684

Answers (1)

BalusC
BalusC

Reputation: 1108722

The HttpServletRequest object is in JSF available by ExternalContext#getRequest().

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
// ...

The ExternalContext by the way also offers some direct methods to get the desired information. Check the methods starting with getRequestXxx() such as getRequestHeaderMap(), getRequestContentType(), etc in the javadoc.

You don't need another servlet for this. JSF has already the FacesServlet as the sole request/response controller.

Upvotes: 4

Related Questions