Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Spring Boot Development: Quick Start with HTTP Handling and Dependency Injection

Tech May 19 2

Java Web Development - SSM Fundamentals: Quick Start, HTTP Request/Response, IOC & DI

Maven Official Repository: https://mvnrepository.comSpring Official Site: https://spring.io

1 Maven

1.1 Introduction & Installation

Maven (official site: http://maven.apache.org/) is an open-source project by Apache, a tool for managing and building Java projects. It's based on the concept of Project Object Model (POM), managing project builds through a small description.

Functions:

  1. Dependancy management: Easily manage project dependencies (jar files), avoiding version conflicts
  2. Unified project structure: Provides standard, unified project structure
  3. Standardized build process: Standard cross-platform (Linux, Windows, MacOS) automated build method

Repository: Used to store resources, managing various jar files

  • Local repository: A directory on your computer
  • Central repository: The globally unique repository maintained by the Maven team. Repository address: https://repo1.maven.org/maven2/
  • Remote repository (private server): Usually set up by company teams as a private repository.

Installation and Configuration

  1. Unzip apache-maven-3.6.1-bin.zip
  2. Configure local repository: Modify <localRepository> in apache-maven-3.6.1-bin/conf/settings.xml to a specified directory
<!-- apache-maven-3.6.1-bin/conf/settings.xml -->
<localRepository>/Users/example/develop/apache-maven-3.9.5/mvn_repo</localRepository>

  1. Configure Alibaba Cloud private server: Modify the <mirrors> tag in apache-maven-3.6.1-bin/conf/settings.xml by adding the following sub-tag
<!-- apache-maven-3.6.1-bin/conf/settings.xml -->
<mirror>
	<id>alimaven</id>
	<name>aliyun maven</name>
	<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
	<mirrorOf>central</mirrorOf>
</mirror>

  1. Configure environment variables: Set MAVEN_HOME to the Maven extraction directory, and add its bin directory to the PATH environment variable

1.2 Creating Maven Projects

Maven coordinates are the unique identifiers for resources, allowing precise location of resources. Use coordinates to define projects or introduce dependenceis needed in projects.

  • groupId: Defines the organization name the current Maven project belongs to (usually domain name reversed, e.g., com.hyplus)
  • artifactId: Defines the current Maven project name (usually module name, e.g., order-service, goods-service)
  • version: Defines the current project version number

1.3 Dependency Management

Dependency refers to jar files required for the current project to run. A project can introduce multiple dependencies.

1.3.1 Configuring Dependencies

Search and copy dependency coordinates from the official repository

  1. Write the <dependencies> tag in pom.xml
  2. Use <dependency> within the <dependencies> tag to introduce coordinates
  3. Define the coordinate's groupId, artifactId, and version
  4. Click the refresh button to introduce the newly added coordinates, which can then be viewed in the Maven panel on the right
<!-- pom.xml -->
<dependencies>
	<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
	<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.2.3</version>
		<scope>test</scope>
	</dependency>

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
</dependencies>

1.3.2 Dependency Transitivity

Direct dependency: Dependency relationship established through dependency configuration in the current project

Indirect dependency: If the dependent resource depends on other resources, the current project indirectly depends on other resources

Right-click and select Diagrams > Show Diagrams… to view current dependency information in chart form

Excluding dependencies: Actively disconnect dependent resources (<exclusions>), and the excluded resources don't need to specify versions

<!-- pom.xml -->
<dependencies>
	<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
	<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.2.10</version>
		<exclusions>    <!-- Excluding dependency (for example only) -->
			<exclusion>
				<groupId>ch.qos.logback</groupId>
				<artifactId>logback-core</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
</dependencies>

1.3.3 Dependency Scope

By default, dependent jar files can be used anywhere. You can set their scope using <scope></scope>:

  1. Valid in main program scope. (Within the main folder)
  2. Valid in test program scope. (Within the test folder)
  3. Whether to participate in packaging and running. (Within the package command scope)
scope value main program test program packaging (running) example
compile (default) Y Y Y log4j
test - Y - junit
provided Y Y - servlet-api
runtime - Y Y jdbc driver

1.3.4 Lifecycle

Maven's lifecycle: Abstracts and unifies the build process for all Maven projects. There are 3 independent lifecycles:

  • clean: Cleanup work.
  • default: Core work, such as: compile, test, package, install, deploy, etc.
  • site: Generate reports, publish sites, etc.

Each lifecycle contains some phases, which are ordered. Later phases depend on earlier phases—within the same lifecycle, when running later phases, all previous phases will run. (Mainly focus on the following 5 phases)

  1. clean: Remove files generated from the previous build
  2. compile: Compile project source code
  3. test: Run tests using an appropriate unit testing framework (junit)
  4. package: Package compiled files, such as: jar, war, etc.
  5. install: Install the project to the local repository

2 Spring Boot Web Introduction

2.1 Spring Overview

Spring (official site: https://spring.io) has evolved into a development ecosystem. Spring provides several sub-projects, each for specific functions.

Spring Boot helps us build applications very quickly, simplifying development and improving efficiency.

The default directory for static resources (html, css, js, etc.) in Spring Boot projects is: static or public under src/main/resources, or directly placed in src/main/resources

2.2 Creating Spring Boot Projects

  1. Create a Spring Boot project and check web development related dependencies.
  2. Define the request handling class RequestController, add method hello, and add annotations
  3. Run the startup class SpringbootWebQuickstartApplication and test
/* RequestController.class */
package com.hyplus.controller;

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

// Request handling class
@RestController
public class RequestController {
   
   
    @RequestMapping("/hello")
    public String hello() {
   
   
        System.out.println("Hello World!");
        return "Hello World!";
    }
}

Add annotation @Slf4j to the class to automatically create a log object member, and use log.info("Query all department data"); within the method to output log information.

3 HTTP Protocol

3.1 Overview

HTTP protocol (Hyper Text Transfer Protocol) defines the rules for data transfer between browsers and servers.

  1. Based on TCP protocol: Connection-oriented, secure.
  2. Based on request-response model: One request corresponds to one response.
  3. Is a stateless protocol: No memory for transaction processing (each request-response is independent). The disadvantage is that data cannot be shared between multiple requests, and the advantage is speed.

3.2 Request Protocol

Request format:

  1. Request line: The firsst line of request data (request method, resource path, protocol)
  2. Request header: From the second line, format key: value
  3. Request body: The last part, where POST requests store request parameters

Request method-GET: Request parameters are in the request line, no request body, e.g., /brand/EindA11?name=OPO&status=1. GET request size is limited. Request method-POST: Request parameters are in the request body. POST request size is unlimited.

@RequestMapping corresponds to derivative annotations for various request methods: @GetMapping, @PostMapping

Common Request Headers Meaning
Host Requested hostname
User-Agent Browser version
Accept Indicates the resource types the browser can receive, such as text/\*, image/\*, or \*/\* for all
Accept-Language Indicates the preferred language of the browser, the server can return web pages in different languages accordingly
Accept-Encoding Indicates the compression types the browser can support, such as gzip, deflate, etc.
Content-Type Data type of the request body
Content-Length Size of the request body (unit: bytes)

3.3 Response Protocol

Response format:

  1. Response line: The first line of response data (protocol, status code, description)
  2. Response header: From the second line, format key: value
  3. Response body: The last part, storing response data (response body)

Status code reference:

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.