1. 程式人生 > >Java web獲取根據url地址訪問相應的方法

Java web獲取根據url地址訪問相應的方法

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mn = req.getServletPath();
        mn = mn.substring(1);
        mn = mn.substring(0, mn.length() - 4);
        Method method = null;
        try {
            method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        try {
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

假定你的工程名稱為projects,你在瀏覽器中輸入請求路徑:

http://127.0.0.1:8080/projects/pages/newForm.jsp

則執行下面向行程式碼後打印出如下結果:
1、 System.out.println(request.getContextPath());
列印結果:/projects
 2、System.out.println(request.getServletPath());
列印結果:/pages/newForm.jsp
 3、 System.out.println(request.getRequestURI());
列印結果:/projects/pages/newForm.jsp
 4、 System.out.println(request.getRealPath("/"));
 JSP servlet API提供了getRealPath(path)方法,返回給定虛擬路徑的真實路徑,如果轉換錯誤,則返回null。

列印結果:C:\Tomcat5.0\webapps\projects\test