Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic URLs in java web application (like in rails)

I'm a Ruby on Rails developer programming a web application in Java. I am trying to achieve something similar to what is achieved in Rails. In Rails it is possible to call a link using localhost:8000\Users\1 when Users is a Model and 1 is the id of a specific user. I would like to get the same kind of thing in Java.

I am working in an MVC type design where my JSP pages are the view and my Servlets are the controllers. I created a servlet called Users which renders the users.jsp page now i can get to that page using the URL localhost:8000\projectName\Users, i would like to route localhost:8000\projectName\Users\1 to the page user.jsp while the appropriate Servlet will handle sending into the page the correct user (with id=1).

Any idea how I can achieve this?

I'm doing this in a University project and am not allowed to use any frameworks. I also would rather something i could code rather than install.

like image 705
Nachshon Schwartz Avatar asked Oct 21 '25 14:10

Nachshon Schwartz


2 Answers

now i can get to that page using the URL localhost:8000\projectName\Users, i would like to route localhost:8000\projectName\Users\1 to the page user.jsp while the appropriate Servlet will handle sending into the page the correct user (with id=1).

Simple. Map the servlet on an URL pattern of /Users/* instead of /Users. You can then grab the path info (the part after /Users in the URL, which is thus /1 in your example) as follows:

String pathInfo = request.getPathInfo();
// ...

You can just forward to users.jsp the usual way.

Long id = Long.valueOf(pathInfo.substring(1));
User user = userService.find(id);
request.setAttribute("user", user);
request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
like image 91
BalusC Avatar answered Oct 23 '25 05:10

BalusC


I would try this via a servlet and servlet mappings like that in web.xml

<servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.example.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/Users</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/Users/*</url-pattern>
</servlet-mapping>

Than in your UserServlet try to get the full URL and parse it to your needs. Example:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) {

   String url = reg.getRequestURL();

   //... get last part after slash and parse it to your id

}

See http://download.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletRequest.html for further documentation on the request and how its parameters can be retrieved

like image 22
powerMicha Avatar answered Oct 23 '25 04:10

powerMicha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!