dynamic URLs in java web application (like in rails)

筅森魡賤 提交于 2019-12-06 02:00:41

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);

UrlRewriteFilter is like mod_rewrite but for Tomcat. You can use it to make your URLs SEO-friendly. You can also use Apache+mod_rewrite+Tomcat.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!