2

I'm using a Webservlet and I would like to pass parameters in the url itself. Something like

@WebServlet("/profile/{id}")
public class ProfileServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        String idstr = req.getParameter("id");
        int id = idstr == null ? (int)req.getSession().getAttribute("userid") : Integer.parseInt(idstr);
        Profile profile = ProfileDAO.getForId(id);
        req.setAttribute("profile",profile);
        req.getRequestDispatcher("/WEB-INF/profile.jsp").forward(req,res);
    }
}

But I can't seem to find anything in the documentation that allows me to do this. I know I could do /profile?idstr=1234 or something, but is there a way I can slap it into the URL with WebServlet? Or do I need a different framework to do this...

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • It will be much easier to just use any RESTful webservice implementation: spring-ws / apache-cxf.. Otherwise as far as I know you need to parse the values out of the URL on your own and dispatch the correct function based on parsing results – odedsh Nov 16 '13 at 20:31

1 Answers1

0

I was looking myself for this long enough, and found the solution. You can try getting the url, that is currently put into browser url, for example:

../profile/this_id

You can't get this

this_id

in a simple way, but because of internal servlet forward dispatching, which is not always bound to. Sometimes request.getRequestURI() works as needed, you can check it:

String url = null;
url = (String) request.getAttribute("javax.servlet.forward.request_uri");
url = url == null ? ((HttpServletRequest) request).getRequestURI() : url;

or

request.getAttribute("javax.servlet.include.request_uri")

in case you use <jsp:include tag> If you URL is

www.example.com/profile/Ted

the result will be

profile/Ted

so you can simply get what you need. For more info look here Java HttpServletRequest get URL in browsers URL bar

Community
  • 1
  • 1
Natal
  • 154
  • 2
  • 10