Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF provide very basic REST get method

Is there a way to have a doGet method in a @ManagedBean and define a URL on which this bean will react.

I am using JSF and want to provide a really basic feed, but for this I need to react on a get request.

I wrote it with normal servlets first, but now I noticed that I need information from another ManagedBean therefore I need a @ManagedProperty - hence JSF...

My questions:

  • Is there a URLPattern annotation or similar?

  • Is there a doGet method that is similar to the Servlet's doGet?

like image 271
Franz Kafka Avatar asked Nov 01 '25 22:11

Franz Kafka


2 Answers

If you want a RESTful web service, use JAX-RS (e.g. Jersey) instead of JSF.

Or, if you just want "pretty" (REST-like) URLs for JSF, use PrettyFaces.

like image 76
BalusC Avatar answered Nov 03 '25 14:11

BalusC


Assuming servlets...

If you're relying on the JSF context, the trick will be to get the FacesServlet to execute the code. The FacesServlet is responsible for creating and destroying the request context.

Here is the managed bean we want to invoke:

@ManagedBean @RequestScoped
public class Restlike {
  public void respond() {
   FacesContext context = FacesContext.getCurrentInstance();
   ExternalContext ext = context.getExternalContext();
   HttpServletResponse response = (HttpServletResponse) ext.getResponse();
   response.setContentType("text/plain; charset=UTF-8");
    try {
      PrintWriter pw = response.getWriter();
      pw.print("Hello, World!");
    } catch (IOException ex) {
      throw new FacesException(ex);
    }
    context.responseComplete();
  }
}

Here is the placeholder view that will execute the code. resty.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<metadata xmlns="http://java.sun.com/jsf/core">
  <event type="preRenderView" listener="#{restlike.respond}"/>
</metadata>

Hitting resty.faces doesn't look very RESTful, but it is trivial to handle with a filter:

@WebFilter("/rest/*")
public class RestyFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain) throws IOException, ServletException {
    request.getRequestDispatcher("/resty.faces").forward(request, response);
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void destroy() {} 
}

The resultant URL will look something like http://host/context/rest


This solution is a bit of a hack and only applicable to servlet environments. A better approach might be to add a custom ResourceHandler but I haven't spent much time investigating that part of the API.

like image 27
McDowell Avatar answered Nov 03 '25 12:11

McDowell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!