一般情况下我们获取请求相关信息,我们通过servlet相关api就能完成,有时我们需要在纯se环境中得到url字符串中想要的信息,如域名、虚拟目录。下面直接贴出代码:

package com.bs.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlUtil {

    /**
     * 从url中匹配虚拟目录(除去协议、域名、端口号和参数部分)     
     * @param url
     * @param containProjectName
     *            是否去掉项目名
     * @return
     */
    public static String getURI(String url, boolean containProjectName) {
        String regx = "(?:https?://)(?:(?:\\w+\\.){2,3}|[a-zA-Z0-9]+)(?:\\w+)(?::[0-9]+)?" + (containProjectName ? "(?:/\\w+/)" : "")
                + "([^?]*)";
        Pattern p = Pattern.compile(regx);
        Matcher matcher = p.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    /**
     * 匹配域名
     * 如url为http://192.168.10.36:2829/appweb/script/plugin/ueditor/jsp/upload1/20170901/41281504250668218.jpg
     * 返回192.168.10.36
     * 
     * @param url
     * @return
     */
    public static String getHost(String url) {
        Pattern p = Pattern.compile("(?:https?://)((\\w+\\.){2,3}\\w+|[a-zA-z0-9]+)(?::[0-9]+)?");
        Matcher matcher = p.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static void main(String[] args) {
        String path = "http://localhost:2829/script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg?t=3";
        System.out.println(getURI(path,false));///script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg
        System.out.println(getHost(path));//localhost

        path="http://localhost:2829/app/script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg?t=3";
        System.out.println(getURI(path,true));//script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg
        System.out.println(getHost(path));//localhost

        path="http://www.baidu.com:2829/app/script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg?t=3";
        System.out.println(getURI(path,true));///script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg
        System.out.println(getHost(path));//www.baidu.com

        path="http://www.baidu.com:2829/app/script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg?t=3";
        System.out.println(getURI(path,true));//script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg
        System.out.println(getHost(path));//www.baidu.com

        path="http://192.168.10.36:2829/app/script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg?t=3";
        System.out.println(getURI(path,true));//script/plugin/ueditor/jsp/upload1/20170918/95421505699068820.jpg
        System.out.println(getHost(path));//192.168.10.36
    }
}

我们也可以取出协议、端口号、请求参数等,应该不难,因为暂时不需要这些信息,所以就没做这个功能了。