Popular Searches
Popular Course Categories
Popular Courses

Understanding Web Servers and Application Servers

Understanding Web Servers and Application Servers

Advanced Java and Enterprise Web Application Architecture

Understanding Web Servers and Application Servers

Course: Advanced Java Training

Topic: Understanding Web Servers and Application Servers

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Web Servers and Application Servers

Web servers and application servers are important components of modern web application architecture. They receive requests, process information, and deliver responses to users through web browsers, mobile applications, or other clients.

In Java enterprise development, a web server may serve static resources and forward dynamic requests, while an application server or servlet container executes application components and handles business operations. Some products combine these responsibilities in one platform.

Understanding these servers helps developers build, deploy, configure, secure, and troubleshoot Java web applications.

Learning Objectives

  • Understand the purpose of web servers and application servers.
  • Identify the differences between static and dynamic content processing.
  • Learn how HTTP requests and responses move through a web application.
  • Understand Java servlet containers and enterprise application servers.
  • Explore Apache HTTP Server, Nginx, Apache Tomcat, and Spring Boot deployment.
  • Learn about ports, reverse proxies, load balancing, security, and troubleshooting.

2. What Is a Web Server?

A web server is software that accepts HTTP or HTTPS requests from clients and returns appropriate responses. It commonly serves static files such as HTML, CSS, JavaScript, images, fonts, and downloadable documents.

A web server can also forward requests to an application server when application logic is required.

Main Responsibilities

  • Listen for incoming HTTP and HTTPS requests.
  • Serve static website files.
  • Manage connections and request routing.
  • Support TLS/SSL termination and HTTPS configuration.
  • Apply access rules, request limits, and security headers.
  • Forward dynamic requests to backend application services when configured.
  • Record access logs and error logs.

Examples of Web Servers

Web Server Common Uses
Apache HTTP Server Hosting websites, configuring virtual hosts, URL rewriting, and proxying requests.
Nginx Serving static content, reverse proxying, TLS termination, and load balancing.
Microsoft IIS Hosting web applications in Windows-based environments.
Caddy Web serving and automated HTTPS configuration in supported deployments.

3. What Is an Application Server?

An application server provides a runtime environment for application code and supporting services. It processes dynamic requests, executes business logic, coordinates data access, and may provide services such as transactions, security, connection pooling, messaging, and resource management.

In Java development, the term can refer broadly to a runtime that hosts application code. More specifically, a full Jakarta EE application server provides a range of enterprise APIs and container-managed services. A servlet container such as Apache Tomcat supports web components but does not provide every service of a full Jakarta EE application server.

Main Responsibilities

  • Execute application code and business rules.
  • Process dynamic HTTP requests through servlets, controllers, or framework endpoints.
  • Connect to databases and other backend services.
  • Manage application components and runtime resources.
  • Support authentication and authorization integration.
  • Provide transaction, messaging, or persistence services when supported by the platform.
  • Expose application logs, metrics, and diagnostic information.

Examples of Java Application Runtimes

Platform Description
Apache Tomcat A servlet container commonly used to run Java web applications.
Eclipse GlassFish An implementation of Jakarta EE that supports enterprise application deployment.
WildFly An application server for Java enterprise applications.
Oracle WebLogic Server An enterprise application server used in business environments.
IBM WebSphere An enterprise application platform available in different product editions.
Spring Boot embedded server A server runtime packaged with a Spring Boot application, commonly Tomcat, Jetty, or Undertow depending on configuration.

4. Difference Between a Web Server and an Application Server

Feature Web Server Application Server
Primary purpose Handle HTTP requests and serve web content. Run application code and support dynamic business operations.
Typical workload Static resources and request forwarding. Business logic, data processing, and application services.
Static files Usually a core responsibility. May serve them, depending on the runtime and configuration.
Dynamic processing Usually forwards complex processing to a backend. Executes application components or invokes application logic.
Database access Not normally its primary responsibility. Frequently coordinates database access through application code or managed resources.
Examples Apache HTTP Server, Nginx, IIS. WildFly, GlassFish, WebLogic, WebSphere.
Java web support Often integrates with a Java runtime through a proxy or connector. May host servlets, frameworks, and enterprise components.

Important: These roles overlap. Apache Tomcat can accept HTTP requests and serve static files while also running Java servlets. A Spring Boot application can include an embedded web server, so a separate front-end web server is not always required.

5. Static Content and Dynamic Content

Static Content

Static content is returned as a file or resource without running application-specific business logic for each request. Examples include logos, stylesheets, JavaScript bundles, and public HTML files.

GET /images/logo.png HTTP/1.1
Host: example.com

The server locates the requested resource, checks access rules, and returns the file with an appropriate HTTP status and content type.

Dynamic Content

Dynamic content is generated or selected through application logic. For example, an order history page may require authentication, database queries, business rules, and response serialization.

GET /api/orders/1001 HTTP/1.1
Host: example.com
Accept: application/json

The application processes the request, retrieves the permitted order details, and returns a response such as JSON.

6. How a Web Application Request Works

  1. A user enters a URL or interacts with a web application.
  2. The client resolves the domain name through DNS when necessary.
  3. The client establishes a network connection and, for HTTPS, performs a TLS handshake.
  4. The request reaches a web server, reverse proxy, or application server.
  5. The server checks the request path, headers, and configured routing rules.
  6. Static requests may be answered directly. Dynamic requests may be forwarded to a Java application runtime.
  7. The application validates input, checks authorization, executes business logic, and accesses required services.
  8. The server returns an HTTP response with a status code, headers, and an optional body.
  9. The client renders the page or processes the returned data.

Example Architecture

Browser or Mobile Client
          |
       HTTPS
          |
Web Server / Reverse Proxy
          |
   Java Application Runtime
          |
  Service and Business Logic
          |
   Repository / Data Access
          |
        Database

This architecture is common, but it is not mandatory. Small applications may combine the web server and application runtime in one process, while larger systems may use multiple proxy, application, and database layers.

7. Understanding Java Servlet Containers

A servlet container is a runtime component that manages Java servlets and other supported web components. It receives or accepts HTTP requests, maps them to the correct servlet, manages the servlet lifecycle, and sends the generated response back to the client.

Apache Tomcat is a widely used example of a Java servlet container. It can run independently as an HTTP server and can also be placed behind a separate web server or reverse proxy. It is not a full Jakarta EE application server. Read the Apache Tomcat documentation.

Important Servlet Container Responsibilities

  • Load and initialize servlet classes.
  • Call servlet lifecycle methods such as init(), service(), and destroy().
  • Map request URLs to application endpoints.
  • Provide HTTP request and response objects.
  • Manage sessions, filters, listeners, and application configuration.
  • Coordinate request handling and manage runtime resources.

Example Servlet

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().write("Hello from a Java servlet!");
    }
}

When the application is deployed to a compatible servlet container, a GET request to /hello invokes the servlet and returns a plain-text response. The imports shown use the Jakarta Servlet namespace; older Java EE applications may use the javax.servlet namespace, depending on the container version.

8. Understanding HTTP Ports and Server Connections

A port identifies a communication endpoint on a host. Web servers and application runtimes listen on configured ports so that clients or other services can connect to them.

Port Common Use
80 Default port for HTTP.
443 Default port for HTTPS.
8080 Common development port for Tomcat and Java web applications.
8443 Common alternative HTTPS port in development or internal environments.
3306 Default MySQL database port.
5432 Default PostgreSQL database port.

These are common defaults, not mandatory values. The actual port depends on server configuration, deployment environment, and network policy.

Example URL

http://localhost:8080/myapp/hello
  • http is the protocol.
  • localhost refers to the local machine.
  • 8080 is the port.
  • /myapp is the application context path in this example.
  • /hello is the endpoint path.

9. Deploying a Java Application to Tomcat

Java web applications are commonly packaged as WAR files (Web Application Archives) or deployed using an appropriate build and release process. A WAR file can contain compiled classes, libraries, web resources, and application configuration.

Typical Deployment Steps

  1. Install a compatible JDK and a supported Tomcat version.
  2. Build the application using Maven, Gradle, or another suitable build tool.
  3. Confirm that the application targets the correct Servlet API and Java version for the chosen container.
  4. Generate the WAR file or follow the deployment method required by the project.
  5. Deploy the artifact using an approved deployment process.
  6. Start or restart the runtime when required.
  7. Review application and server logs for startup errors.
  8. Test the deployed endpoints and verify the expected response.

Example Maven Build Command

mvn clean package

This command cleans previous build output and packages the application according to the Maven project configuration. The generated artifact is typically found under the target directory.

Deployment note: A WAR built for one major servlet namespace may not work unchanged on a container that expects another namespace. Check compatibility before deploying.

10. Web Servers and Spring Boot Applications

Spring Boot simplifies Java application setup by allowing an embedded server to run inside the application. Depending on the project's dependencies and configuration, the application may use an embedded Tomcat, Jetty, or Undertow server.

This approach allows developers to run an application without installing a separate application server for local development. In production, a separate reverse proxy or load balancer may still be used for TLS termination, routing, traffic management, or security controls.

Example Spring Boot Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello from Spring Boot!";
    }
}

With a correctly configured Spring Boot project and compatible dependencies, the endpoint can be accessed at http://localhost:8080/hello when the application uses port 8080.

Changing the Application Port

# application.properties
server.port=9090

After this configuration is applied, the application normally listens on port 9090 instead of its default port, unless another configuration source overrides the setting.

11. Reverse Proxy and Load Balancing

A reverse proxy accepts client requests and forwards them to one or more backend services. It can hide internal server details, terminate HTTPS, route traffic, and apply selected security or traffic-management rules.

A load balancer distributes requests among multiple backend instances to improve availability and handle traffic. Some reverse proxies also provide load-balancing functionality.

Example Deployment Structure

Clients
   |
HTTPS
   |
Reverse Proxy / Load Balancer
   |                 |
Java Instance A   Java Instance B
   |                 |
   +------ Database -+

Benefits

  • Distributes traffic across multiple application instances.
  • Allows backend instances to be replaced or updated more easily.
  • Can centralize TLS termination and selected routing policies.
  • Can improve resilience when health checks and failover are correctly configured.
  • Can reduce direct exposure of backend application ports.

A reverse proxy does not automatically make an application secure or highly available. Correct health checks, timeout settings, network restrictions, session handling, and deployment design are still necessary.

12. Virtual Hosts and Request Routing

Virtual hosting allows one server or server instance to serve multiple websites or hostnames. Routing rules select the appropriate website or backend based on information such as the requested hostname, path, or other configured conditions.

For example, a deployment might route www.example.com to a public website and api.example.com to a Java API service. The exact configuration depends on the chosen web server or proxy.

Example Routing Concept

www.example.com  -> Website frontend
api.example.com  -> Java REST API
admin.example.com -> Restricted admin application

Administrative applications should have appropriate authentication, authorization, network restrictions, and monitoring. A different hostname alone is not a security boundary.

13. Configuration and Environment Management

Server configuration controls how an application accepts traffic, connects to services, and behaves in each environment. Common settings include ports, context paths, database connections, logging, thread pools, timeouts, TLS certificates, and proxy rules.

Good Configuration Practices

  • Keep development, testing, staging, and production settings separate.
  • Use environment variables or a secrets manager for sensitive configuration.
  • Do not store database passwords, private keys, or API secrets in public source repositories.
  • Document port numbers, context paths, dependencies, and deployment procedures.
  • Validate configuration changes in a non-production environment first.
  • Maintain backups of important configuration files and establish a rollback procedure.
  • Monitor resource use and tune thread pools and connection pools according to measured workload.

14. Security Considerations

Both web servers and Java application runtimes need careful security configuration. Security should be applied in layers, including network controls, TLS, application-level validation, authentication, authorization, and secure operations.

  • HTTPS: Use correctly configured TLS certificates for protected traffic.
  • Authentication: Verify the identity of users or services where required.
  • Authorization: Check permissions for protected resources and operations.
  • Input validation: Validate data on the server and use safe database access practices.
  • Least privilege: Run services with only the permissions they require.
  • Restricted administration: Protect management consoles and deployment interfaces.
  • Updates: Keep the JDK, server runtime, libraries, and operating system patched.
  • Secrets management: Protect credentials and rotate them when necessary.
  • Logging: Record useful security events without exposing passwords, tokens, or sensitive personal data.
  • Network controls: Avoid exposing internal application or database ports directly to the public internet unless explicitly required and appropriately protected.

15. Performance and Scalability

Server performance depends on many factors, including application design, CPU, memory, network latency, database response time, request concurrency, and runtime configuration. Simply increasing the number of threads does not guarantee better performance.

Performance Improvement Techniques

  • Measure response times and throughput before changing configuration.
  • Cache suitable static resources and frequently requested data where safe.
  • Use connection pooling for database access when supported by the chosen stack.
  • Optimize expensive database queries and add appropriate indexes.
  • Configure request and connection timeouts to prevent indefinite waits.
  • Use compression where it provides a measurable benefit and is safely configured.
  • Scale vertically or horizontally based on observed resource constraints.
  • Monitor memory, CPU, garbage collection, thread usage, and error rates.
  • Use load testing to identify bottlenecks before major releases.

16. Logging and Monitoring

Logs and monitoring data help developers identify failures, diagnose performance problems, and understand application behavior. A useful operational setup combines server logs, application logs, metrics, and, where appropriate, distributed traces.

Common Log Categories

Log Type Purpose
Access logs Record HTTP requests, response status codes, and request timing when configured.
Application logs Record application events, warnings, and exceptions.
Server logs Help diagnose startup, connector, deployment, and runtime problems.
Security logs Capture relevant authentication, authorization, and security events.

Monitor important indicators such as request rate, latency, error rate, CPU and memory use, active connections, and database response time. Establish alerts that help teams act before service disruption becomes severe.

17. Common Server Problems and Troubleshooting

Problem Possible Cause Suggested Checks
Connection refused Service is stopped or listening on a different port. Check process status, listener configuration, and network rules.
HTTP 404 Not Found Incorrect URL, context path, route, or missing resource. Verify deployment path, endpoint mapping, and resource location.
HTTP 500 Internal Server Error Unhandled exception or backend failure. Inspect application logs and exception stack traces.
HTTP 502 Bad Gateway Proxy cannot obtain a valid response from the backend. Check backend availability, proxy target, protocol, and logs.
HTTP 503 Service Unavailable Service is unavailable, overloaded, or marked unhealthy. Check health status, capacity, deployments, and dependencies.
Address already in use Another process uses the configured port. Identify the process or configure a permitted unused port.
Application fails to start Configuration error, incompatible Java version, missing dependency, or port conflict. Read startup logs and verify runtime and dependency compatibility.
Slow responses Slow queries, resource contention, excessive external calls, or inefficient code. Measure latency by component and profile the bottleneck.

Practical Troubleshooting Checklist

  1. Confirm that the relevant server process is running.
  2. Verify the configured hostname, port, protocol, and application path.
  3. Check firewall rules and network connectivity.
  4. Inspect startup and application logs around the time of failure.
  5. Test the endpoint locally and then through the proxy, if one exists.
  6. Check database and external service availability.
  7. Review recent configuration changes and deployments.
  8. Apply a fix, retest the affected endpoint, and document the result.

18. Practical Exercise: Run a Java Web Application

Objective: Run a small Java web application and understand how a server receives and processes an HTTP request.

Exercise Steps

  1. Create a basic Spring Boot web project using compatible Java and Spring Boot versions.
  2. Add the web dependency required by the project.
  3. Create a controller with a GET endpoint.
  4. Run the application from the IDE or using the project's build tool.
  5. Open the endpoint in a browser or test it with an HTTP client.
  6. Change the configured port and restart the application.
  7. Review the console output and application logs.
  8. Stop the application and observe how the endpoint becomes unavailable.

Example Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusController {

    @GetMapping("/status")
    public String status() {
        return "Application is running";
    }
}

With the application running on port 8080, visit http://localhost:8080/status. The expected response body is Application is running.

Exercise Questions

  • Which server runtime accepts the request in this example?
  • What happens if the application is configured to use a port that is already occupied?
  • How would you determine why the endpoint returns a 404 status?
  • What role could Nginx or Apache HTTP Server play in front of this application?

19. Mini Project: Deploy a Java REST API Behind a Reverse Proxy

Project goal: Create a simple Java REST API and understand how a reverse proxy can route client requests to the application.

Requirements

  • Create a Spring Boot application with health and data endpoints.
  • Configure the application to listen on an internal port.
  • Configure a local reverse proxy to forward a chosen URL path to the application.
  • Test the API both directly and through the proxy.
  • Review application and proxy logs.
  • Document the configuration, startup procedure, and troubleshooting steps.

Expected Learning Outcomes

  • Understand the relationship between a reverse proxy and a Java application runtime.
  • Recognize the difference between public and internal service endpoints.
  • Practice diagnosing incorrect proxy targets and unavailable backend services.
  • Understand why production deployments require secure configuration and monitoring.

20. Interview Questions and Answers

Q1. What is a web server?

A web server receives HTTP or HTTPS requests and returns responses. It commonly serves static files and may forward dynamic requests to backend applications.

Q2. What is an application server?

An application server provides a runtime for application code and may supply enterprise services such as transactions, security integration, resource management, and messaging.

Q3. What is the main difference between a web server and an application server?

A web server is primarily associated with handling web traffic and serving content, while an application server focuses on executing application logic and supporting application services. In practice, their roles can overlap.

Q4. Is Apache Tomcat a web server or an application server?

Tomcat is primarily a Java servlet container that can also serve HTTP requests and static resources. It is not a full Jakarta EE application server.

Q5. What is a servlet container?

A servlet container manages servlet components, maps requests to them, invokes their lifecycle methods, and coordinates request and response handling.

Q6. What is a reverse proxy?

A reverse proxy accepts client requests and forwards them to backend services. It can provide routing, TLS termination, and other traffic-management features.

Q7. What is load balancing?

Load balancing distributes requests across multiple backend instances according to configured rules and health information.

Q8. Why is port 8080 commonly used in Java development?

Port 8080 is a common alternative HTTP port used by development servers and Java web applications. It is a convention, not a requirement.

Q9. What is the difference between HTTP 404 and HTTP 500?

HTTP 404 means the requested resource or route was not found. HTTP 500 indicates that the server encountered an unexpected condition while processing the request.

Q10. What is the purpose of HTTPS?

HTTPS protects communication between the client and server using TLS, helping provide confidentiality and integrity and allowing the client to authenticate the server certificate.

Q11. Can Spring Boot run without a separately installed Tomcat server?

Yes. A typical Spring Boot web application can include an embedded server, allowing the application to run as a standalone process.

Q12. How would you troubleshoot an application that is not responding?

Check whether the process is running, verify ports and network rules, inspect server and application logs, test backend dependencies, and measure resource use to locate the cause.

21. Best Practices and Quick Revision

Best Practices

  • Choose a server platform that matches the application's requirements and APIs.
  • Verify Java and server compatibility before deployment.
  • Keep public-facing services and internal application services appropriately separated when required by the architecture.
  • Use HTTPS and secure server configuration.
  • Restrict management endpoints and sensitive network ports.
  • Use structured logging and monitor service health.
  • Set sensible timeouts and resource limits.
  • Test deployments and maintain a rollback plan.
  • Keep server software and dependencies updated.

Quick Revision Checklist

  • Can you explain the purpose of a web server?
  • Can you describe what an application server does?
  • Can you distinguish a servlet container from a full Jakarta EE application server?
  • Can you explain how a request reaches a Java controller or servlet?
  • Can you describe ports, context paths, and endpoint mappings?
  • Can you explain the purpose of a reverse proxy and load balancer?
  • Can you identify common causes of 404, 500, 502, and 503 errors?
  • Can you explain the basics of secure deployment and monitoring?

22. Conclusion

Web servers and application servers play complementary roles in Java enterprise application development. Web servers commonly manage incoming web traffic, static content, and request forwarding, while application runtimes execute business logic and support dynamic application behavior. Technologies such as Apache HTTP Server, Nginx, Apache Tomcat, Spring Boot, and full Jakarta EE application servers are used in different combinations according to the application's needs.

By understanding request routing, server configuration, deployment, security, monitoring, and troubleshooting, Java developers can build and maintain reliable web applications.

To explore training options, visit the Advanced Java Training Course, register for a course demo, or browse the JustAcademy website.

Previous Next
whatsapp