Welcome to the definitive implementation of a production-ready Java Spring Web Server that solves the complex challenges of modern web application development. This project demonstrates industry best practices for security, stateless authentication, and bidirectional communication.
- Stateless Authentication with JWT π - Implements the OAuth 2.0 authorization framework using JSON Web Tokens for secure, scalable authentication
- Defense-in-Depth Security π‘οΈ - Protects authentication tokens with HTTP-only secure cookies, mitigating XSS vulnerabilities
- Seamless Session Management β‘ - Transparent token refresh mechanism maintains user sessions without disrupting experience
- Polyglot Persistence πΎ - Configurable connections to multiple database systems (PostgreSQL, MySQL) with transaction support
- Real-time Bidirectional Communication π‘ - Full WebSocket implementation for instant data exchange and notifications
- Production-Ready Architecture ποΈ - Built on Spring Boot's enterprise-grade foundation with comprehensive security controls
- Java 17+ β - Modern language features including records, pattern matching, and enhanced switch expressions
- Spring Boot 3.x π - Streamlined application bootstrapping and configuration
- Spring Security π - Comprehensive security framework with secure defaults
- Spring WebFlux βοΈ - Reactive programming model for highly concurrent applications
- Spring Data JPA π - Advanced ORM with sophisticated query capabilities
- JWT Library ποΈ - Industry-standard JWT implementation with robust signature verification
- Spring WebSocket π - Enterprise-grade WebSocket implementation with STOMP messaging
- Hibernate ποΈ - Feature-rich JPA provider with extensive customization options
- JDK 17+
- Maven 3.8+
- PostgreSQL/MySQL instance
-
Clone & Navigate: π
git clone https://github.com/MrDay2Day/spring-advanced-webserver.git cd spring-advanced-webserver
-
Configure Your Environment: βοΈ Create an
application-dev.properties
file based on the template below:# Environment Variables # Spring Server Variables server.port=3077 server.tomcat.max-http-header-size=1048576 # JWT Variables jwt.secret=your-very-long-and-secure-secret-key jwt.refresh.secret=your-very-long-and-secure-secret-key-for-refresh jwt.websocket.secret=your-very-long-and-secure-secret-key-for-websocket jwt.cookie.name=jwtToken jwt.expiration.seconds=30 jwt.cookie.refresh.name=jwtRefreshToken jwt.expiration.refresh.seconds=5184000 jwt.cookie.secret=this_is_a_secure_string_to_sign_cookies_from_this_server # PostGreSQL Variables postgresql.conn.host=postgresql_host postgresql.conn.database=database postgresql.conn.username=username postgresql.conn.password=password # MySQL Variables mysql.conn.host=mysql_host mysql.conn.database=database mysql.conn.username=username mysql.conn.password=password # HikariCP (Connection Pool) Settings (Optional but Recommended) spring.datasource.hikari.maximum-pool-size=10 spring.datasource.hikari.minimum-idle=2 spring.datasource.hikari.idle-timeout=30000 spring.datasource.hikari.connection-timeout=30000
-
Build & Run: π οΈ
mvn clean install mvn spring-boot:run -Dspring-boot.run.profiles=dev
-
Verify Installation: β The server will start at
http://localhost:3077
Endpoint | Method | Description | Request Body | Response |
---|---|---|---|---|
/auth/register |
POST | Create new user account | {"username":"user","password":"pass","email":"[email protected]"} |
User details with 201 status |
/auth/login |
POST | Authenticate user | {"username":"user","password":"pass"} |
Sets HTTP-only cookies, returns user profile |
/auth/logout |
POST | End user session | None | Clears auth cookies, returns 200 status |
/auth/refresh-websocket-token |
GET | Generate WebSocket token | None (requires auth cookie) | {"token":"ws-jwt-token"} |
Endpoint | Method | Description | Authentication |
---|---|---|---|
/secure/get |
GET | Test authenticated access | Required |
/secure/send-websocket-message |
POST | Send real-time message | Required |
Connect to the WebSocket endpoint with your authentication token:
ws://localhost:3077/ws?token={your-ws-token}
Send a test message through the REST API:
POST /secure/send-websocket-message
{
"userId": "3",
"message": "Real-time notification test"
}
- Registration: User credentials are securely hashed with BCrypt before storage
- Login: Credentials verified, JWT tokens generated (access + refresh)
- Token Storage: JWTs stored in HTTP-only cookies with secure and SameSite flags
- Auto-Refresh: Interceptors transparently refresh tokens before expiration
- WebSocket Auth: Specialized short-lived tokens for WebSocket connections
- CSRF Protection: Spring Security's CSRF token validation
- XSS Mitigation: Content-Security-Policy headers and HTTP-only cookies
- Input Validation: Bean Validation (JSR 380) for request payload validation
- Rate Limiting: Custom interceptors prevent brute force attacks
- Secure Headers: Implements OWASP recommended security headers
The multi-database configuration enables:
- Separation of concerns (e.g., user data vs. application data)
- Cross-database transactions with JTA when needed
- Database-specific optimization strategies
- Read-write splitting for high-load scenarios
Our WebSocket implementation provides:
- Authenticated connections with JWT verification
- STOMP messaging protocol for pub/sub capabilities
- Message filtering based on user context
- Reconnection handling with session recovery
- Optimized broadcast capabilities for high-volume messaging
Spring Boot revolutionizes Java web development through:
Spring Boot eliminates boilerplate by providing sensible defaults while allowing customization where needed. This approach dramatically reduces development time and cognitive overhead.
The embedded Tomcat/Jetty/Undertow server eliminates deployment complexity and enables true "java -jar" deployment with minimal configuration.
Spring Boot analyzes your classpath and automatically configures components based on detected libraries, reducing configuration to the absolute minimum.
Built-in actuator endpoints provide metrics, health checks, and environment information essential for production monitoring.
Spring Boot carefully curates compatible dependency versions, eliminating "dependency hell" and ensuring components work together seamlessly.
Spring's annotation-based programming model provides clear component classification:
- @Configuration: Classes that define beans through @Bean methods
- @Component: Generic Spring-managed component
- @Controller/@RestController: Web request handlers
- @Service: Business logic encapsulation
- @Repository: Data access components with exception translation
- @Entity: JPA-managed database entity
- @Autowired: Dependency injection marker (constructor injection preferred)
- @RequestMapping/@GetMapping/@PostMapping: HTTP request mapping
- @ExceptionHandler: Centralized exception management
The application demonstrates Spring's @Async capabilities for background processing tasks.
Strategic caching with Spring Cache and EhCache reduces database load for frequently accessed data.
Includes unit, integration, and end-to-end tests with JUnit 5, Mockito, and Spring Test.
- Binary message support
- Message compression
- Client heartbeat monitoring
- Session affinity for clustered deployments
βββ .gitignore
βββ pom.xml
βββ README.md
βββ src/
β βββ main/
β β βββ java/
β β β βββ org/
β β β βββ file/
β β β βββ apiResponse/
β β β β βββ ApiResponse.java
β β β β βββ HttpServletErrorResponse.java
β β β βββ controllers/
β β β β βββ AuthController.java
β β β β βββ CookieController.java
β β β β βββ MainController.java
β β β βββ database/
β β β β βββ DatabaseType.java
β β β β βββ DataSourceConfig.java
β β β β βββ DatabaseConnection.java
β β β β βββ DatabaseQueryExecution.java
β β β β βββ DatabaseDynamicQueryExecution.java
β β β β βββ models/
β β β β βββ User.java
β β β β βββ UserPublicInfo.java
β β β βββ middleware/
β β β β βββ apiGlobals/
β β β β β βββ GlobalsExceptionHandler.java
β β β β βββ filters/
β β β β | βββ FilterConfig.java
β β β β | βββ CookieFilter.java
β β β β βββ interceptors/
β β β β βββ AuthInterceptor.java
β β β β βββ InterceptorConfig.java
β β β β βββ MainInterceptor.java
β β β βββ utils/
β β β | βββ BcryptHashing.java
β β β | βββ JwtUtil.java
β β β | βββ GenerateCookie.java
β β β βββ Main.java
β β β βββ webSocket/
β β β βββ MainWebSocketHandler.java
β β β βββ WebSocketConfig.java
β β βββ resources/
β β βββ application.properties
β βββ test/
β βββ GitIgnore.java
βββ .idea/
βββ External Libraries
- GraphQL API implementation βοΈ
- OAuth 2.0 social login integration π
- Event-driven architecture with Spring Cloud Stream βοΈ
- Kubernetes deployment manifests π³
- Comprehensive monitoring with Micrometer and Prometheus π
We welcome contributions! Please see our Contributing Guide for details on our development process and pull request workflow.
This project is licensed under the MIT License - see the LICENSE file for details.