Steven Roose
Steven Roose

Reputation: 2769

How to pass on parameters from pretty URL to JSP pages?

I trying to do two things at once and I don't seem to find answers that can do both.

I'm trying this:

I want URLs ending in /user/{parameter} to be mapped to a JSP page user.jsp where I can access the parameter.

I find ways to pass parameters from the web.xml file to the JSP using this method

<init-param>
<param-name>someParam</param-name>
<param-value>itsValue</param-value>
</init-param>

And I find ways to create URL filters and map them to Java Servlets.

What I need is a combination. Also, what I found on passing URL parameters to Servlets wasn't too detailed either, so a good reference on that would also be more than welcome!

Upvotes: 1

Views: 2987

Answers (2)

BalusC
BalusC

Reputation: 1108682

I want URLs ending in /user/{parameter} to be mapped to a JSP page user.jsp where I can access the parameter.

Map a servlet on /user/* and use HttpServletRequest#getPathInfo() to extract the path info.

E.g.

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo(); // "/{parameter}"
        // ...
        request.getRequestDispatcher("/WEB-INF/user.jsp").forward(request, response);
    }

}

That's basically all. Use the usual String methods like substring() and/or split() to break down the path info in usable parts.

Upvotes: 4

Blessed Geek
Blessed Geek

Reputation: 21614

Use a base-url servlet to parse the URL and perform a conditional servlet forwarding to the appropriate JSP.

request.getRequestDispatcher().forward(JSPurl)

Let us say you have a URL branch /sales/. Under this URL branch, you would allow the following URLs to to be serviced by /implemented/usersales.jsp :

  • /sales/liquour/users/{region}
  • /sales/liquour/soft/users/{region}
  • /sales/toiletries/users/{type}

and the following URLs to be serviced by /implemented/products.jsp - /sales/groceries/products/{section} - /sales/groceries/meat/products/{region} - /sales/groceries/vegetables/beans/products/{region}

You would have a web.xml servlet mapping for servlet class org.myorg.SalesHandler to be mapped to /sales/.

In the service method override in org.myorg.SalesHandler servlet class, analyse the URL pattern (using regexp or otherwise) and then conditionally forward the request using

request.getRequestDispatcher().forward(JSPurl)

JAX-RS

But why would you do that when we have jax-rs?

How to forward from a JAX-RS service to JSP?.

JAX-RS may seem daunting at first, but it is actually very simple and intuitive to implement.

Upvotes: 1

Related Questions