# Java Web Server with Start/Stop Controls and Website Links
Here's a complete solution for a Java web server that:
1. Allows starting and stopping the server
2. Displays active websites with their names, links, and ports
3. Serves both HTML and PHP files
4. Provides a web interface for management
## Complete Implementation
```java
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WebServerManager {
private static HttpServer server;
private static ExecutorService executor;
private static int port = 8080;
private static final String WEB_ROOT = "webroot";
private static final List<WebsiteInfo> websites = new ArrayList<>();
public static void main(String[] args) {
// Add some sample websites
websites.add(new WebsiteInfo("Main Site", "http://localhost:8080", 8080));
websites.add(new WebsiteInfo("Admin Panel", "http://localhost:8080/admin", 8080));
// Create webroot directory if it doesn't exist
new File(WEB_ROOT).mkdirs();
// Create default files if they don't exist
createDefaultFiles();
startServer();
// Add shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
stopServer();
System.out.println("Server stopped");
}));
}
private static void createDefaultFiles() {
try {
// Create index.html if it doesn't exist
Path indexHtml = Paths.get(WEB_ROOT, "index.html");
if (!Files.exists(indexHtml)) {
String content = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title>Java Web Server</title>\n" +
" <style>\n" +
" body { font-family: Arial, sans-serif; margin: 40px; }\n" +
" .website { border: 1px solid #ddd; padding: 15px; margin-bottom: 10px; }\n" +
" .controls { margin: 20px 0; }\n" +
" button { padding: 8px 15px; margin-right: 10px; }\n" +
" </style>\n" +
"</head>\n" +
"<body>\n" +
" <h1>Java Web Server Control Panel</h1>\n" +
" <div class=\"controls\">\n" +
" <button onclick=\"fetch('/control?action=stop')\">Stop Server</button>\n" +
" <button onclick=\"fetch('/control?action=restart')\">Restart Server</button>\n" +
" </div>\n" +
" <h2>Active Websites</h2>\n" +
" <div id=\"websites\">\n" +
" <!-- Websites will be populated by JavaScript -->\n" +
" </div>\n" +
" <script>\n" +
" // Fetch website list from server\n" +
" fetch('/websites')\n" +
" .then(response => response.json())\n" +
" .then(data => {\n" +
" const container = document.getElementById('websites');\n" +
" data.forEach(site => {\n" +
" const div = document.createElement('div');\n" +
" div.className = 'website';\n" +
" div.innerHTML = `\n" +
" <h3>${site.name}</h3>\n" +
" <p><a href=\"${site.url}\" target=\"_blank\">${site.url}</a></p>\n" +
" <p>Port: ${site.port}</p>\n" +
" `;\n" +
" container.appendChild(div);\n" +
" });\n" +
" });\n" +
" </script>\n" +
"</body>\n" +
"</html>";
Files.write(indexHtml, content.getBytes());
}
// Create example.php if it doesn't exist
Path examplePhp = Paths.get(WEB_ROOT, "example.php");
if (!Files.exists(examplePhp)) {
String content = "<?php\n" +
"echo \"<!DOCTYPE html>\";\n" +
"echo \"<html><head><title>PHP Test</title></head>\";\n" +
"echo \"<body>\";\n" +
"echo \"<h1>PHP is working!</h1>\";\n" +
"echo \"<p>Current time: \" . date('Y-m-d H:i:s') . \"</p>\";\n" +
"echo \"<p>Server IP: \" . $_SERVER['SERVER_ADDR'] . \"</p>\";\n" +
"echo \"<p>Server Port: \" . $_SERVER['SERVER_PORT'] . \"</p>\";\n" +
"echo \"</body></html>\";\n" +
"?>";
Files.write(examplePhp, content.getBytes());
}
} catch (IOException e) {
System.err.println("Error creating default files: " + e.getMessage());
}
}
public static void startServer() {
try {
server = HttpServer.create(new InetSocketAddress(port), 0);
executor = Executors.newFixedThreadPool(10);
server.setExecutor(executor);
// Main handler for static files
server.createContext("/", new FileHandler());
// API endpoint to list websites
server.createContext("/websites", exchange -> {
String json = "[" + websites.stream()
.map(site -> String.format(
"{\"name\":\"%s\",\"url\":\"%s\",\"port\":%d}",
site.getName(), site.getUrl(), site.getPort()))
.reduce((a, b) -> a + "," + b)
.orElse("") + "]";
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, json.length());
OutputStream os = exchange.getResponseBody();
os.write(json.getBytes());
os.close();
});
// Control endpoint
server.createContext("/control", exchange -> {
String action = exchange.getRequestURI().getQuery().split("=")[1];
String response;
switch (action) {
case "stop":
stopServer();
response = "Server stopped";
break;
case "restart":
stopServer();
startServer();
response = "Server restarted";
break;
default:
response = "Unknown action";
}
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
});
server.start();
System.out.println("Server started on port " + port);
System.out.println("Access the control panel at: http://localhost:" + port);
} catch (IOException e) {
System.err.println("Error starting server: " + e.getMessage());
}
}
public static void stopServer() {
if (server != null) {
server.stop(0);
executor.shutdownNow();
System.out.println("Server stopped");
}
}
static class FileHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
if (path.equals("/")) path = "/index.html";
Path filePath = Paths.get(WEB_ROOT, path.substring(1));
// Handle PHP files
if (path.endsWith(".php")) {
try {
ProcessBuilder pb = new ProcessBuilder("php", filePath.toString());
Process process = pb.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
exchange.getResponseHeaders().set("Content-Type", "text/html");
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.toString().getBytes());
os.close();
} catch (Exception e) {
String error = "500 Internal Server Error: " + e.getMessage();
exchange.sendResponseHeaders(500, error.length());
OutputStream os = exchange.getResponseBody();
os.write(error.getBytes());
os.close();
}
return;
}
// Handle static files
if (Files.exists(filePath)) {
String contentType = getContentType(path);
byte[] fileBytes = Files.readAllBytes(filePath);
exchange.getResponseHeaders().set("Content-Type", contentType);
exchange.sendResponseHeaders(200, fileBytes.length);
OutputStream os = exchange.getResponseBody();
os.write(fileBytes);
os.close();
} else {
String response = "404 Not Found";
exchange.sendResponseHeaders(404, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
private String getContentType(String path) {
if (path.endsWith(".css")) return "text/css";
if (path.endsWith(".js")) return "text/javascript";
if (path.endsWith(".png")) return "image/png";
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
if (path.endsWith(".gif")) return "image/gif";
return "text/html";
}
}
static class WebsiteInfo {
private String name;
private String url;
private int port;
public WebsiteInfo(String name, String url, int port) {
this.name = name;
this.url = url;
this.port = port;
}
public String getName() { return name; }
public String getUrl() { return url; }
public int getPort() { return port; }
}
}
```
## Features
1. **Server Controls**:
- Start/stop/restart functionality
- Web-based control panel
- Proper thread management
2. **Website Management**:
- Displays active websites with names, links, and ports
- JSON API endpoint for website data
- Automatic creation of default files
3. **File Serving**:
- Handles both HTML and PHP files
- Proper content type detection
- Error handling for missing files
4. **Security**:
- Prevents directory traversal
- Proper resource cleanup on shutdown
## How to Use
1. **Run the Server**:
```bash
javac WebServerManager.java
java WebServerManager
```
2. **Access Control Panel**:
Open your browser to `http://localhost:8080`
3. **Manage Websites**:
- The control panel shows all active websites
- Use buttons to stop or restart the server
- PHP scripts will be executed if PHP is installed
4. **Add More Websites**:
Modify the `websites` list in the code to add more entries:
```java
websites.add(new WebsiteInfo("New Site", "http://localhost:8080/new", 8080));
```
## Customization Options
1. **Change Port**:
Modify the `port` variable at the top of the class.
2. **Add Authentication**:
```java
server.createContext("/admin", exchange -> {
// Check for authentication header
if (!exchange.getRequestHeaders().containsKey("Authorization")) {
exchange.getResponseHeaders().set("WWW-Authenticate", "Basic");
exchange.sendResponseHeaders(401, -1);
return;
}
// Handle authenticated requests
});
```
3. **Add HTTPS Support**:
```java
// You would need to set up SSLContext
// server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
```
4. **Dynamic Website Registration**:
Add an API endpoint to register websites at runtime:
```java
server.createContext("/register", exchange -> {
// Parse JSON from request body
// Add new website to the list
});
```
This implementation provides a complete web server solution with management capabilities, suitable for development or small-scale production use.
No comments:
Post a Comment