Securing the web module
The first resource we want to protect is the web resource, a servlet, as follows:
package net.lucamasini.security; @WebServlet(name="MyWorkServlet", urlPatterns={"/myprotectedresource"}) public class MyProtectedServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Principal userPrincipal = req.getUserPrincipal(); resp.getWriter().println(userPrincipal!=null?userPrincipal.getName(): "anonymous"); } }
Here we can see the power of Java EE 6: we don't need to write XML to declare a servlet and to bind it to a URL, a single annotation is enough. Now, after compiling and launching, the deploy goal will allow us to call http://localhost:7001/chapter3-web/myprotectedresource
and see the string anonymous
; this means our servlet has been deployed and the user is still anonymous.
Now we can go a step further and protect the web...