问题
I'm trying to register a HttpServlet that will receive parameters (don't really care if it is via POST or GET, altough POST preferred obviously). Pretty much just extending what is depicted here:
http://www.javaworld.com/javaworld/jw-06-2008/jw-06-osgi3.html?page=3
And here:
http://www.peterfriese.de/osgi-servlets-a-happy-marriage/
I'm not using still declarative registration, first want to see it working, then I'll do the other stuff.
Doubt arises when calling:
httpService.registerServlet("/helloworld", new RestServlet(), null, null);
Not sure how to tell HttpService that the server will accept params. Besides, is it mandatory to create a HttpServlet with new() everytime a servlet is registered or can I reuse the same for different aliases? I'm asking because maybe it is possible to use some wildcard in the alias argument and then let the HttpServlet object deal with whatever comes in the HttpRequest...?
Any help/suggestions/thoughts are welcome!
Regards, Alex
回答1:
I don't know very much about OSGI, however it seems to me to be more a pure servlet problem. I took a look at the links you provided and hope I can help you.
First, I think you do not need to tell the HttpService that it will accept params. When you use servlets, you can simply extract the request parameters:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getParameter(paramName); // get a request parameter
}
Second, I think you can use the same Servlet for multiple "aliases". This seems like a kind of servlet mapping to me: You can use multiple mappings (/helloworld, /helloxyz etc.) for one and the same servlet.
回答2:
- You can register multiple times with the same servlet if you ignore the servlet init.
- If you want to see all, just register /
- The whiteboard is a lot easier and a much better approach.
The Http Service will find the longest path and call that servlet. So / is a fallback.
Example hello world servlet without whiteboard:
@Component
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws IOException {
rsp.getWriter().write( ("Hello World " + rq.getParameter("name")).getBytes());
}
@Reference
void setHttp(HttpService http) { http.registerService("/hello", null, null); }
}
Example, now with whiteboard:
@Component(provide=Servlet.class, properties="alias=/hello")
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws IOException {
rsp.getWriter().write( ("Hello World " + rq.getParameter("name")).getBytes());
}
}
This kind of things are really easy to play with in bndtools. Create a small project with DS, then create a bndrun file with the web console. Won't regret it.
来源:https://stackoverflow.com/questions/14837260/registering-servlet-in-osgi-that-receives-parameters