You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot实现将端口号注入静态HTML资源页面

解决Spring Boot静态HTML注入端口号问题

方法一:使用Thymeleaf模板引擎(推荐)

Spring Boot对Thymeleaf原生支持,只需简单改造即可实现变量注入:

  • 添加Thymeleaf依赖到pom.xml(Maven):
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 将原/resources/setting/index.html移动到/resources/templates/setting/目录下(Thymeleaf默认模板路径)
  • 修改HTML中的硬编码端口,替换为Thymeleaf表达式:
    比如原代码是const port = 8080;,改成:
<script>
const port = [[${serverPort}]];
</script>
  • 创建控制器传递端口参数:
@Controller
@RequestMapping("/setting")
public class SettingController {
    @Value("${server.port:8080}")
    private Integer serverPort;

    @GetMapping
    public String index(Model model) {
        model.addAttribute("serverPort", serverPort);
        return "setting/index";
    }
}
  • 访问路径/setting会自动映射到模板页面,无需额外配置静态资源路径

方法二:静态资源内容替换(无需模板引擎)

如果不想引入模板引擎,可以通过Spring的资源转换器实现占位符替换:

  • 创建资源转换器类:
@Component
public class PortPlaceholderTransformer implements ResourceTransformer {
    @Value("${server.port:8080}")
    private String serverPort;

    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
        if (resource.getFilename().equals("index.html") && resource.getURL().getPath().contains("/setting/")) {
            String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            content = content.replace("{{SERVER_PORT}}", serverPort);
            return new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8));
        }
        return transformerChain.transform(request, resource);
    }
}
  • 配置WebMvc注册转换器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private PortPlaceholderTransformer portTransformer;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/setting/**")
                .addResourceLocations("classpath:/setting/")
                .resourceChain(true)
                .addTransformer(portTransformer);
    }
}
  • 修改HTML中的硬编码端口为占位符{{SERVER_PORT}},比如:
<input type="text" value="{{SERVER_PORT}}" id="portInput">

方法三:前端JS动态请求后端接口

通过AJAX请求后端接口获取端口号,适合需要动态刷新的场景:

  • 编写后端接口返回端口:
@RestController
@RequestMapping("/api")
public class ApiController {
    @Value("${server.port:8080}")
    private Integer serverPort;

    @GetMapping("/server-port")
    public Integer getServerPort() {
        return serverPort;
    }
}
  • 在HTML的JS中发起请求替换端口:
<script>
fetch('/api/server-port')
    .then(response => response.json())
    .then(port => {
        // 替换页面中的端口元素
        document.getElementById('portInput').value = port;
        // 或者更新相关业务逻辑中的端口值
    });
</script>

内容的提问来源于stack exchange,提问作者giangig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:05:43