Notice
Recent Posts
Recent Comments
Link
반응형
Tags more
Archives
관리 메뉴

Daily stories on Tech • Beauty • Travel

Web Development in Java 본문

Tech/Java Web Development

Web Development in Java

nandarasol 2025. 5. 8. 09:21
반응형

 

Java Application Servers

What is servlet?

Think of a servlet as a small Java program that runs on the server and handles requests and generates responses for web applications. It’s like a waiter in a restaurant — when you (the client) make a request (like ordering food), the servlet (the waiter) takes your request, processes it, and serves you the response (the food).

Here’s a breakdown of what a servlet does:

  1. Receives Requests: Servlets receive requests from clients (usually web browsers) via HTTP (Hypertext Transfer Protocol). These requests can be for various actions, such as retrieving a webpage, submitting a form, or performing some other operation.
  2. Processes Requests: Once a servlet receives a request, it processes it according to the logic defined in its code. This could involve retrieving data from a database, performing calculations, or generating dynamic content based on the request parameters.
  3. Generates Responses: After processing the request, the servlet generates a response to send back to the client. This response typically includes HTML content, which is what the client’s web browser renders to display the webpage. The response may also include other types of data, such as images, JSON, or XML, depending on the nature of the request.
  4. Sends Responses: Finally, the servlet sends the response back to the client over the network using HTTP. The client’s web browser receives the response and displays the content to the user.

Servlets are often used in combination with JavaServer Pages (JSP) to build dynamic web applications. Servlets handle the business logic and data processing, while JSP files handle the presentation layer by defining the structure and layout of the web pages.

In summary, servlets are Java programs that run on the server and handle requests and responses for web applications. They play a critical role in building dynamic and interactive web applications by processing requests from clients and generating appropriate responses.

Programming for the Web in Java

A web server’s primary role is listening for HTTP requests and handling them with application logic, sending an HTTP response to the client that indicates the result of the operation. Simple HTTP servers host directories of HTML files directly, sending files in response to requests for specific URLs. This is enough for static websites with no dynamic server operations, but modern web apps support users accounts, complex interactions, and persistent data. Java application servers make these features more accessible by hosting many individual applications, managing them over a common interface, the servlet. This allows developers to focus on application logic and features, with HTTP request handling and routing handled by the server.

Spring provides additional sets of libraries that integrate with the servlet interface to provide applications with even more utilities that focus on database access, security, and HTML generation, and it’s the tool we’ll use to build our web applications.

  • HTTP Request/Response: HTTP, or HyperTextTransferProtocol, is a binary data format for communication between programs over the web. It can be broken down into two basic message types: requests and responses. Clients send requests for resources to servers, which respond with the requested data. (https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages)
  • HTTP GET and POST: Every HTTP request has an important header that determines its method. GET and POST are two of the most common; GET indicates a request for data from the server, and POST represents a request to "post" new data to the server - this usually represents some action on server data like submitting search terms, posting an update, or adding new data to the server.
Java SE
When most people think of the Java programming language, they think of the Java SE API. Java SE’s API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.
Java EE
The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.
 

The Java Application Server

 

A Java Application Server is a pluggable architecture that can host many deployed applications at once. It provides utilities like multi-threading, request filtering, and resource sharing to each application. Those applications must expose endpoints that handle the requests routed to them by the server.

The Structure of a Java Application Server

Key Terms

  • HTTP: Hypertext Transfer Protocol. A binary protocol that originally defined the mechanics of requesting and sending HTML over the internet.
  • Web Server: A program that listens for and responds to HTTP requests over the internet
  • Application Server: A program that hosts other applications, forwarding incoming requests to the appropriate application according to a filter. Provides shared access to resources and multi-threading.
  • Pluggable Architecture: A pluggable architecture refers to any piece of software that allows parts of it to be added, replaced, and removed. Usually, this is achieved through a common interface for every “pluggable” component. Sometimes the architecture can even replace components at runtime, as is the case with Servlets in an Application Server.
  • Threads/Threading: These terms come from concurrent programming — a thread is essentially one track of computation, and multi-threading is running multiple threads in parallel. This gets a little complicated because your CPU has a limited number of physical cores that can process instructions in parallel, while the number of threads you can have can be many more than your computer has cores, but that’s a topic for another time!

Java Servlets

The Servlet class is the main connection between the apps you develop and the application server they run on. By extending Servlet, you can create endpoints that handle incoming requests in a way specific to your application needs, and you can map specific request URLs to specialized servlets by adding entries to a web.xml file. The app server uses this configuration to instantiate and manage your servlets. It interacts with each through three standard methods, init, service, and destroy:

  • service is where requests are handled, and the server will call this method when a request is routed to the servlet it's called on.
  • init is where initialization of the servlet is handled, and the server will call this method directly after instantiating the servlet.
  • destroy is where servlet resource cleanup is handled, and is called directly before the server terminates the servlet instance.

A quick note on Java Application Files:

When you compile a Java program and package it to be run, the Java compiler creates what is called a Java ARchive, or JAR file. This file contains a compressed file hierarchy, with folders that represent Java packages that contain Java .class files, which are the compiled versions of .java source code files. It can also contain arbitrary resource files, either at the root level or deeply nested in the package hierarchy. These files often contain metadata related to the app or library contained in the JAR file, which can be read by any program that interacts with the JAR.

When you want to deploy an app to an app server, you have to package it as a Web application ARchive, or WAR file. A WAR file is almost identical to a JAR file, but includes configuration files specific to web applications. When we copy a WAR file into the deployment directory of an app server, the server unpackages it, looks for a web.xml file, and uses that file to find the classes and resources required by the application. This uses advanced Java features like reflection and class loading to programmatically load Java class definitions and instantiate them which is quite a nifty trick! It allows us to dynamically load, start, stop, and replace any number of applications in a web server at any time.

Key Terms

  • Endpoints: An endpoint is the address at which a client can reach a specific part of a server’s functionality. Usually, this is a URL path, the /words/and/slashes that follow the domain of a URL, like .com or .org.
  • Servlet: A class defined as a part of the Java: Enterprise Edition specification. Provides an implementable interface for web server request processing, defining a service method that the server invokes on an instantiated servlet to handle a ServletRequest and ServletResponse object for an incoming request. The servlet also defines lifecycle methods for the server to invoke when initializing or destroying a servlet.
  • JAR: A Java Archive file, which stores compiled .class files in a folder hierarchy that matches the code's package structure. Includes an optional manifest file.
  • WAR: A variation on the JAR for web applications, which optionally includes web resources like HTML files and configuration files like web.xml for servlet registration/mapping.

Spring Applications

Spring is an application framework, which means that instead of choosing when to invoke it from your application, you choose when it invokes your application code. This pattern of software development is called Inversion of Control (IoC), and it’s powerful because it allows developers to develop specialized application components and use Spring to connect them with each other using dependency injection. This is good for clean, separated code and for code reuse. This is evident when looking at the vast number of Spring modules and Spring-integrated third-party tools that are available. This course focuses on a few of them:

  • Spring MVC, a generic web controller library for Spring that supports a wide variety of utilities to simplify the handling of HTTP requests
  • Thymeleaf, a third party template engine that can integrate with Spring MVC to simplify the generation of web pages as responses to HTTP requests
  • Spring Security, a generic authentication library for Spring that can integrate with many different credential sources and authentication protocols to automatically manage request authentication and security contexts
  • MyBatis, a third-party database access library that provides simple SQL/Java mapping tools that can be defined in Spring components

The End of Boilerplate: Spring Boot

So Spring adds a lot of features, but it still sounds like a lot of configuration. We still have to deploy it to an application server, right? And we still have to create a servlet for Spring to live in. It also sounds like getting all of these modules and utilities to work together might take some work.

In the past, Spring did require a lot of configuration, but over time, the development world has moved towards a convention-over-configuration approach. Spring Boot is a project that provides an a-la-cart Spring experience, complete with a web page for generating and downloading starter projects based on the application needs. Most Spring Boot applications today also contain an embedded application server with a default, pre-configured servlet definition. All you have to do to run your Spring-enabled code as a server is to run a main method.

With the rise of containerized architectures like Docker, this style of application development has become as popular as the pluggable application server, and in this course, we’ll be exclusively using this mode. However, if you do want to deploy your Spring Boot application to a traditional application server, there are built-in tools that allow you to package the application as a standard WAR file.

Key Terms

  • IoC: Inversion of Control, which is the practice of designing libraries as application runners. This allows developers to focus on application-specific logic and rely on IoC containers to connect application components with one another, eliminating a lot of boilerplate and encouraging a clean separation of development concerns.

Spring Starter Packs Setup

Spring is a collection of open-source libraries that solve common web development problems. But how do we get those libraries? We’ll be using Maven, a dependency management tool that lets us define dependencies on open-source libraries based on their names and version numbers. We define those in a file in our projects called pom.xml, which Maven reads and uses to download the required libraries. We can also have our projects inherit dependencies from some base project, which is a feature that Spring Boot uses to make setting up a new Spring project easy as pie. We'll be using Spring Initializr, an online project generator, to choose specific Spring dependencies to add to new Spring projects.

Spring Boot is best experienced with the help of Spring Initializr, an official project generator. You can use it to configure metadata and build properties of a project as well as what starter dependencies you want to include. These include:

  • Spring Dev Tools: utilities including hot reloading changed code into a running application
  • Spring MVC: web layer utilities that make developing server-side web apps easy
  • Spring Data: a common interface for many different types of database access
  • And many more Once you’ve selected your dependencies and chosen your language, build tool, and project identifiers, Spring Initializr will generate a zip file that includes a ready-to-run server with all of the choices you made reflected in its pom.xml file, as well as the package structure.

Here are some examples of Java boilerplates :

  1. Spring Boot — Spring Boot is a popular Java framework for building web applications, and it includes a variety of starter projects to help developers get started quickly. These starter projects provide pre-configured settings and dependencies for common use cases, such as web applications, RESTful services, and microservices.
  2. Maven — Maven is a build automation tool for Java projects, and it includes a project creation tool that generates a basic project structure with pre-configured settings and dependencies. Developers can customize this structure to fit their specific requirements.
  3. Hibernate — Hibernate is an ORM (Object-Relational Mapping) framework for Java that simplifies database access. It includes a variety of boilerplate code for setting up database connections, defining mappings between Java objects and database tables, and executing database queries.
  4. JavaServer Faces (JSF) — JSF is a Java web framework that simplifies the development of user interfaces for web applications. It includes a variety of boilerplate code for creating pages, forms, and other user interface components.
  5. Java Servlets — Java Servlets are a Java API for handling HTTP requests and responses. They are used to build web applications in Java. There are a variety of boilerplate code available for Java Servlets that provide pre-configured settings and dependencies for common use cases.

Key Terms

  • Maven: A dependency management system and project build tool for Java. Provides a standardized way to define dependencies between projects and include them in the project build path.
  • POM: The Project Object Model that Maven uses to represent the dependency and build configuration of a project. Usually, this refers to the pom.xml configuration file found in a Maven project.
  • Dependency Management System: Any tool that automates the downloading and linking of external packages to a software development project. Most languages these days either provide one officially or have a community-accepted standard.

Here’s an example pom.xml that includes our new dependency:

<?xml version="1.0" encoding="UTF-8"?>

      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.2.7.RELEASE</version>
     <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.udacity.jdnd</groupId>
  <artifactId>course1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>course1</name>
  <description>My Super Cool Project</description>
  <properties>
     <java.version>14</java.version>
  </properties>
  <dependencies>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
     </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
           <exclusion>
              <groupId>org.junit.vintage</groupId>
              <artifactId>junit-vintage-engine</artifactId>
           </exclusion>
        </exclusions>
     </dependency>
  </dependencies>
  <build>
     <plugins>
        <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
     </plugins>
  </build>
</project>

Glossary

  • HTTP Request/Response: HTTP, or HyperTextTransferProtocol, is a binary data format for communication between programs over the web. It can be broken down into two basic message types: requests and responses. Clients send requests for resources to servers, which respond with the requested data. Read more about the protocol here.
  • HTTP GET and POST: Every HTTP request has an important header that determines its method. GET and POST are two of the most common; GET indicates a request for data from the server, and POST represents a request to "post" new data to the server - this usually represents some action on server data like submitting search terms, posting an update, or adding new data to the server.
  • HTTP: Hypertext Transfer Protocol. A binary protocol that originally defined the mechanics of requesting and sending HTML over the internet.
  • Web Server: A program that listens for and responds to HTTP requests over the internet
  • Application Server: A program that hosts other applications, forwarding incoming requests to the appropriate application according to a filter. Provides shared access to resources and multi-threading.
  • Pluggable Architecture: A pluggable architecture refers to any piece of software that allows parts of it to be added, replaced, and removed. Usually, this is achieved through a common interface for every “pluggable” component. Sometimes the architecture can even replace components at runtime, as is the case with Servlets in an Application Server.
  • Threads/Threading: These terms come from concurrent programming — a thread is essentially one track of computation, and multi-threading is running multiple threads in parallel. This gets a little complicated because your CPU have a limited number of physical cores that can process instructions in parallel, while the number of thread you can have can be many more than your computer has cores, but that’s a topic for another time!
  • Endpoints: An endpoint is the address at which a client can reach a specific part of a server’s functionality. Usually, this is a URL path, the /words/and/slashes that follow the domain of a URL, like .com or .org.
  • Servlet: A class defined as a part of the Java: Enterprise Edition specification. Provides an implementable interface for web server request processing, defining a service method that the server invokes on an instantiated servlet to handle a ServletRequest and ServletResponseobject for an incoming request. The servlet also defines lifecycle methods for the server to invoke when initializing or destroying a servlet.
  • JAR: A Java Archive file, which stores compiled .class files in a folder hierarchy that matches the code's package structure. Includes an optional manifest file.
  • WAR: A variation on the JAR for web applications, which optionally includes web resources like HTML files and configuration files like web.xml for servlet registration/mapping.
  • IoC: Inversion of Control, which is the practice of designing libraries as application runners. This allows developers to focus on application-specific logic and rely on IoC containers to connect application components with one another, eliminating a lot of boilerplate and encouraging a clean separation of development concerns.
  • Maven: A dependency management system and project build tool for Java. Provides a standardized way to define dependencies between projects and include them in the project build path.
  • POM: The Project Object Model that Maven uses to represent the dependency and build configuration of a project. Usually, this refers to the pom.xml configuration file found in a Maven project.
  • Dependency Management System: Any tool that automates the downloading and linking of external packages to a software development project. Most languages these days either provide one officially or have a community-accepted standard.

Key Terms

  • Web servers and how early servers were single-function programs that could host files, serve web pages, and expose databases to external connections.
  • Java application servers, which provides a pluggable architecture for applications to interface with, granting access to shared resources and multi-threaded request processing.
  • Spring framework, a family of libraries that build on the abstractions of the application server to support many third-party integrations to provide easy abstractions for common web development tasks.
  • Spring Boot, a convention-over-configuration approach to Spring app development that provides defaults for many Spring configuration options in order to provide a smoother development experience.
  • Spring Initializr, the official project generator for Spring Boot, which allows developers to specify an application’s metadata and dependencies and receive a fully-configured Spring Boot project, ready for development.

Summary — Spring Boot Dependencies

  • Spring Web This dependency helps to build RESTful web services using the Spring MVC. It uses Apache Tomcat as the default container.
  • Thymeleaf It is a server-side Java template engine for both web and standalone applications that allows you to show HTML web pages to a client and populate them with data directly using the server code.
  • Spring Security It is a dependency that allows custom authentication and access-control framework for the web application.
  • MyBatis It is a persistence framework for having SQL support. MyBatis couples objects with SQL statements using an XML descriptor or annotations.
반응형

'Tech > Java Web Development' 카테고리의 다른 글

Testing  (0) 2025.05.12
Data Persistence & Security  (1) 2025.05.11
Spring MVC and Thymeleaf  (1) 2025.05.10
Spring boot for web development  (0) 2025.05.09
Spring boot  (1) 2025.05.07