2

If the urlPatterns controls basic URL rewrite, can I not use .htaccess to rewrite the URL? I'm looking at this code: http://www.objectdb.com/tutorial/jpa/eclipse/ee/servlet

...
@WebServlet(name = "GuestServlet", urlPatterns = {"/guest"})
public class GuestServlet extends HttpServlet {
...

This page works great when I access http://localhost:8080/Guestbook/guest, but what if I wanted to do http://localhost:8080/Guestbook/guest/edit?id=4, how would I set that up in this controller?

In PHP the logical steps would be http://localhost:8080/Guestbook/controller/function. In java it seems like I can only use doGet(), is this right?

I'm trying to envision how the overall URL structure affects the execution of controllers.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ben
  • 60,438
  • 111
  • 314
  • 488

2 Answers2

2

Use an URL pattern of /guest/* and use HttpServletRequest#getPathInfo() to extract the path information.

Here's a kickoff example (trivial checks omitted):

@WebServlet("/guest/*")
public class GuestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] pathInfo = request.getPathInfo().split("/");
        String action = pathInfo[1]; // edit
        String id = pathInfo[2]; // 4
        // ...
    }

}

Invoking http://localhost:8080/Guestbook/guest/edit/4 will set action to edit and id to 4. You could from this step on make use of the strategy pattern to invoke specific business actions.

You could of course also go for an action based MVC framework which abstracts all the servlet boilerplate away, such as Spring MVC.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

resource http://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/annotation/WebServlet.html

basically you need to change

@WebServlet(name = "GuestServlet", urlPatterns = {"/guest"})

to

@WebServlet(name = "GuestServlet", urlPatterns = {"/guest", "/guest/edit"})

now your servlet should handle the "/guest/edit" URL pattern also

  • Do I still need to put all my code within the `doGet()` or can I have say, a `doGetEdit()`? – Ben Dec 07 '11 at 02:29
  • whenever a "get" request is made the doGet() method is invoked, when a "post" is made, doPost() is invoked, for examples please go to http://courses.coreservlets.com/Course-Materials/csajsp2.html and download demos so that it will help you better understand. –  Dec 07 '11 at 02:38