知识问答
java 如何启动本地服务器
2026-11-27 19:39:19
来源:互联网转载
要启动本地服务器,可以通过Java提供的内置API或使用第三方库来实现。下面是两种常用的方法:
方法一:使用Java内置的HttpServer类
导入必要的类:import com.sun.net.httpserver.HttpServer;import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;创建HttpServer对象并指定端口:HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);创建处理请求的处理器(HttpHandler):HttpHandler handler = new HttpHandler() { public void handle(HttpExchange exchange) throws IOException { // 处理请求逻辑 }};将处理器与特定路径关联:server.createContext("/", handler);启动服务器:server.start();方法二:使用第三方库,例如Spring Boot
添加Spring Boot依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>创建一个启动类,并添加@RestController注解:import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestControllerpublic class ServerApplication { public static void main(String[] args) { SpringApplication.run(ServerApplication.class, args); } @RequestMapping("/") public String handleRequest() { // 处理请求逻辑 return "Hello, World!"; }}运行启动类,服务器将在默认端口(8080)上启动。
java服务器
上一篇:iis服务器如何设置net环境
下一篇:cache服务器什么意思