liusheng
2025-04-18 55ede3cff5dbbbcb8675d1592a67f20d598d49e7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.ruoyi.framework.config;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.ServletUtils;
 
/**
 * 服务相关配置
 *
 * @author ruoyi
 */
@Component
public class ServerConfig {
    @Value("${server.port}")
    private String port;
 
    /**
     * 获取完整的请求路径,包括:域名,端口,上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        String domain = getDomain(request);
        //修改一个端口
        domain = replaceAfterSecondColon(domain, port);
        return domain;
    }
 
    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
 
    public static String replaceAfterSecondColon(String str, String replacement) {
        int firstColonIndex = str.indexOf(":");
        if (firstColonIndex != -1) {
            int secondColonIndex = str.indexOf(":", firstColonIndex + 1);
            if (secondColonIndex != -1 && secondColonIndex + 1 < str.length()) {
                // 获取第二个“:”前的部分
                String beforeSecondColon = str.substring(0, secondColonIndex + 1);
                // 返回替换后的字符串
                return beforeSecondColon + replacement;
            }
        }
        return str;
    }
}