Nidheesh
Nidheesh

Reputation: 4562

Extract jsp page from the whole URL

I am using request.getHeader("Referer") to get the previous page URL from where I came. But I am getting here the complete URL for example http://hostname/name/myPage.jsp?param=7. Is there any way to extract myPage.jsp?param=7from the whole URL? Or I need to process the string?I just need myPage.jsp?param=7.

Upvotes: 1

Views: 627

Answers (3)

Bekzat Abdiraimov
Bekzat Abdiraimov

Reputation: 110

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

Upvotes: 1

HashimR
HashimR

Reputation: 3843

You can simply reconstruct URL by using this function. Use only the things you need from this function.

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

or If this function does not fulfil your need, then you can always use String manipulation:

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

Pass in /sub/dir/path.html returns path.html

Hope this helps. :)

Upvotes: 2

radai
radai

Reputation: 24202

class URI - http://docs.oracle.com/javase/7/docs/api/java/net/URI.html just build a new URI instance with the string you have (http://hostname/name/myPage.jsp?param=7) and then you can access parts. what you want is probably getPath()+getQuery()

Upvotes: 2

Related Questions