1

request.getHeader("Referer")来た場所から前のページのURLを取得するために使用しています。しかし、私はここで完全なURLを取得していますhttp://hostname/name/myPage.jsp?param=7myPage.jsp?param=7URL全体から抽出する方法はありますか?または、文字列を処理する必要がありますかmyPage.jsp?param=7

4

3 に答える 3

2

class URI - http://docs.oracle.com/javase/7/docs/api/java/net/URI.html 持っている文字列で新しい URI インスタンスを作成するだけです (http://hostname/name/myPage. jsp?param=7) を実行すると、パーツにアクセスできます。あなたが望むのはおそらく getPath()+getQuery() です

于 2012-07-30T05:43:08.133 に答える
2

この関数を使用すると、URL を簡単に再構築できます。この機能から必要なものだけを使用してください。

public static String getUrl(HttpServletRequest req) {
    String scheme = req.getScheme();             // http
    String serverName = req.getServerName();     // hostname.com
    int serverPort = req.getServerPort();        // 80
    String contextPath = req.getContextPath();   // /mywebapp
    String servletPath = req.getServletPath();   // /servlet/MyServlet
    String pathInfo = req.getPathInfo();         // /a/b;c=123
    String queryString = req.getQueryString();          // d=789

    // Reconstruct original requesting URL
    String url = scheme+"://"+serverName+":"+serverPort+contextPath+servletPath;
    if (pathInfo != null) {
        url += pathInfo;
    }
    if (queryString != null) {
        url += "?"+queryString;
    }
    return url;
}

または、この関数がニーズを満たさない場合は、いつでも文字列操作を使用できます。

public static String extractFileName(String path) {

    if (path == null) {
        return null;
    }
    String newpath = path.replace('\\', '/');
    int start = newpath.lastIndexOf("/");
    if (start == -1) {
        start = 0;
    } else {
        start = start + 1;
    }
    String pageName = newpath.substring(start, newpath.length());

    return pageName;
}

/sub/dir/path.html を渡すと、path.html が返されます

お役に立てれば。:)

于 2012-07-30T05:56:27.137 に答える
1
Pattern p = Pattern.compile("[a-zA-Z]+.jsp.*");
Matcher m = p.matcher("http://hostname/name/myPage.jsp?param=7");
if(m.find())
{
     System.out.println(m.group());
}
于 2012-07-30T06:11:07.270 に答える