search

Home  >  Q&A  >  body text

java - JSP怎么生成“动态URL”?

也不知道“动态URL”这种叫法对不对,反正这样的需求也还不会描述。

需求如下:
譬如 http://segmentfault.com/q/1010000002910984 这样的URL,URL中的一串数字(1010000002910984)对应一个问题详情页面,我们暂且认为这也是数据库中的ID,那在JSP怎么达到这样的效果?即,数据库里有很多条数据,以ID标识,希望就是通过一个包含记录的ID的URL来到达详情页面,使用的是JSP技术。其实这样的做法在很多网站都实现了。
现在在下能做到的程度只是一个个JSP页面跳转(每个页面都是写好了的),自己道行不够深,还没想到怎么实现这样的需求。

希望大神指点,先谢谢了。

巴扎黑巴扎黑2882 days ago845

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:59:13

    JSP is a servlet. A better solution is to write a servlet to uniformly schedule requests and act as a route. For example, the entry point of SpringMVC is DispatcherServlet.
    The following is an answer based on the respondent's question. Of course, my way is not the best.
    For example, http://segmentfault.com/q/1010000002910984 uses a servlet to handle all requests under http://segmentfault.com/q/

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * Created by reeco_000 on 2015/6/16.
     */
    @WebServlet(name = "URLServlet",urlPatterns = "/q/*")
    public class URLServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取请求的地址
            String id = request.getRequestURI();
    
            //do something
        }
    }
    

    reply
    0
  • PHPz

    PHPz2017-04-17 13:59:13

    In fact, this should not be done by jsp. It can be easily done by using url rewrite in the web server. Both nginx and apache support it. Tomcat can be configured in web.xml through a UrlRewriteFilter filter.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:59:13

    @netingcn’s answer seems similar. Is it completely possible for the server to do this?
    If you insist on java web background implementation, then set a filter to filter all jsp page requests and change URI to the corresponding page.

    reply
    0
  • Cancelreply