- #java #spring #springboot #스프링부트 #자바 #웹개발 #백엔드 #backend #프로그래밍 #개발자 #개발공부 #코딩공부
- #springboot #springmvc #thymeleaf #javawebdevelopment #webapplication #modelviewcontroller #htmltemplates #formhandling #springcontroller #backenddevelopment #javadeveloper #springboottutorial #프로그래밍 #자바 #웹개발 #스프링부트 #자바웹개발
- #restapi #restfulapi #웹개발 #백엔드개발 #api설계 #웹서버 #서버통신 #프론트백엔드연동 #api란 #개발자공부 #코딩기초 #http요청 #json데이터
- #koreatravel #eastsea #hiddengemkorea #oceanview #travelvibes #koreanseaside #instagramspot
- #git #깃 #git설치 #git초기설정 #git사용법 #버전관리 #versioncontrol #분산버전관리 #distributedversioncontrol #dvcs #중앙집중버전관리 #centralizedvcs #git기본개념 #git기초 #git초보 #commit #커밋 #repository #저장소 #branch #브랜치 #sha #sha해시 #stagingarea #스테이징영역 #workingdirect
- #스프링부트 #자바웹개발 #스프링프레임워크 #자바서블릿 #웹개발입문 #마이바티스 #타임리프 #스프링보안 #자바서버 #스프링mvc #자바ee #maven #pom파일 #웹애플리케이션 #웹아키텍처 #http요청응답 #restfulapi #spring초보 #spring강의 #springinitializr사용법
- #gapyeongtrip #morningcalmgarden #rainydayvibes #flowerlover #springgarden #tulipseason #healingtravel #solotravelspot #koreanature #photospotkorea #gardenwalk #rainydaydate #springinkorea #travelkorea
- #가평카페 #월송카페 #가평감성카페 #유러피안로스터리 #가평데이트코스 #가평빵맛집 #가평핫플 #가평풍경맛집 #감성카페 #한옥카페 #가평브런치 #가평여행 #감성충전 #카페추천 #힐링카페 #mz감성카페
- #스프링부트 #springboot #mybatis #스프링시큐리티 #orm #자바웹개발 #웹보안 #회원가입 #로그인인증 #데이터베이스설계 #웹개발자 #코딩블로그 #백엔드개발 #springsecurity #javaorm #해싱 #암호화 #웹앱보안 #jdbc #hashing #authentication #onionarchitecture
- #평창카페 #감성카페추천 #강원도카페투어 #평창카페게리짐 #자연속카페 #빈티지카페 #유럽감성카페 #디저트맛집 #평창여행 #강원도드라이브 #분위기좋은카페 #평창감성여행 #30대여자여행 #40대여자취향저격 #감성맛집 #카페추천 #강원도핫플 #티스토리카페후기
- #springboot #springboot기초 #스프링부트강의 #springioc #di #의존성주입 #springmvc #스프링mvc #springsecurity #springdata #springjpa
- 너티브루키 #인천카페 #인천디저트 #디저트 #디저트맛집 #두바이초콜릿 #바클라바 #카페 #맛집
- #java #자바 #개발자 #신입개발자 #restapi #스프링부트 #스프링데이터jpa #h2데이터베이스 #dogrestapi #springboot #springdatajpa #h2database
- #도째비골 #동해가볼만한곳 #강원도여행 #감성여행지 #힐링여행 #국내여행추천 #동해바다 #바다뷰맛집 #강원도핫플 #말똥도나쓰 #mz감성카페 #포토존맛집 #데이트코스추천 #사진찍기좋은곳 #바다전망카페
- #가평여행 #아침고요수목원 #수목원데이트 #비오는날감성 #튤립명소 #서울근교여행 #가평데이트코스 #꽃구경명소 #비오는날힐링 #감성사진맛집 #자연힐링 #봄꽃명소 #비오는날데이트 #혼자여행추천 #사진스팟추천
- #springboot #javawebdevelopment #javaservlet #springframework #springmvc #thymeleaf #springsecurity #mybatis #javaee #httprequests #restapi #mavenbuild #webapplicationarchitecture #warvsjar #dependencyinjection #ioc #springinitializr #javabackend #webserv
- #개발공부 #api기초 #신입개발자
- #테스트개발 #junit사용법 #qa #자바단위테스트 #스프링통합테스트 #테스트자동화 #자바 #java #자바개발 #신입개발자 #개발포트폴리오
- #그레이트오션로드여행 #12사도바위 #멜번당일치기코스 #호주멜버른여행 #호주자연명소 #그레이트오션로드투어 #greatoceanroad #twelveapostles #melbournedaytrip
- #싱가포르여행 #가든스바이더베이 #마리나베이샌즈 #머라이언파크 #창이공항주얼 #야경맛집 #야경명소 #라떼아트카페 #싱가포르인증샷 #mrt여행 #여자혼자여행 #감성사진 #트래블로그
- #gapeongcafe #wolsongcafe #koreacafe #aestheticcafe #coffeelovers #europeanroastery #koreatravel #hiddenplaceseoul #mzstyle #healingvibes #hanokcafe #brunchspot #coffeetime #cafestagram #calmvibes
- #cafegerizim #vintagecafe #pyeongchangcafe #koreacafe #cafetour #hiddencafe #dessertcafe #naturecafe #healingplace #vintagestyle #countrysidevibes #peacefulspot #cozyvibes #afternoontea #cafelovers
- #restapi #restful #webdevelopment #backenddevelopment #apiintegration #apiarchitecture #webserver #databaseconnection #httprequests #jsondata #frontendbackend #webapplication
- #springboot #스프링부트 #springframework #스프링프레임워크 #dependencyinjection #의존성주입 #inversionofcontrol #제어의역전 #bean #빈 #component #컴포넌트 #service #서비스 #repository #리포지토리 #applicationcontext #애플리케이션컨텍스트 #configuration
Daily stories on Tech • Beauty • Travel
Web Development in Java 본문
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:
- 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.
- 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.
- 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.
- 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 :
- 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.
- 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.
- 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.
- 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.
- 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 |