Issue
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'sdoGet
?
Solution
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.
Answered By - McDowell
Answer Checked By - Terry (JavaFixing Volunteer)