SpringBoot搭建web項目


1.SpringBoot的優點

  1. 支持內嵌的servlet容器,只需要將項目打包jar包,使用java -jar xxx即可運行項目
  2. 提供大量的start來簡化maven配置
  3. 提供了默認的spring配置
  4. 提供了服務監控工具Actuator

2.使用SpringBoot創建web項目

以IntelliJ IDEA為例子。點擊File-new project,到以下頁面:

選擇Spring Initializer,點擊next,到以下頁面:

輸入正確的項目名稱,使用默認配置一直點擊下一步。到創建項目完成。
項目創建完成后目錄結構如下圖:

其中DemoApplication代碼如下如下:

@SpringBootApplication
   public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

此類中的main方法為springboot項目啟動的入口。
此類中的SpringBootApplication注解可以觸發自動配置Spring功能,並且項目自動掃描此注解標識的類同目錄文件下的所有Spring的bean。

3.創建web接口

pom文件中添加Springboot-web-start依賴:

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

創建Response類用來返回給客戶端數據,代碼如下:

public class Response<T> {

    /**
     * 接口響應代碼
     */
    private int code = 200;

    /**
     * 接口訪問信息
     */
    private String message = "Success";

    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Response{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

創建Controller接口,代碼如下:

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @GetMapping
    public Response<Map<String, Object>> get(){
        Response<Map<String, Object>> response = new Response<>();
        Map<String, Object> user = new HashMap<>();
        user.put("name", "demo");
        user.put("age", 25);
        response.setData(user);
        return  response;
    }
}

其中RestController為組合注解,等於在UserController添加了Controller和ResponseBody兩個注解。
其中GetMapping注解等同於
@RequestMapping(method = RequestMethod.GET)

點擊下圖按鈕啟動項目、

項目啟動后在瀏覽器中輸入:

http://localhost:8080/user

會返回json字符串。返回數據如下:

{
  "code": 200,
  "message": "Success",
  "data": {
    "name": "demo",
    "age": 25
  }
}

至此,已經使用SpringBoot成功搭建起來一個web項目。下面對SpringBoot項目啟動原理分析。

4.SpringBoot的配置介紹

servlet相關配置:

在resource/application.properties文件中添加以下配置更改服務監聽端口和服務環境路徑:

#端口號
server.port=8081
#服務環境路徑
server.servlet.context-path=/demo

添加此配置后重啟服務。在瀏覽器中輸入:

http://localhost:8081/demo/user

可成功訪問接口。

修改banner的內容

SpringBoot默認的banner為:

      .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

可以通過配置修改banner的內容。首先訪問一下網站;

http://patorjk.com/software/taag/#p=display&f=Graffiti&t=demo

輸入文本,生成相應的banner,此處以demo為例生成一下內容:

    .___                     
  __| _/____   _____   ____  
 / __ |/ __ \ /     \ /  _ \ 
/ /_/ \  ___/|  Y Y  (  <_> )
\____ |\___  >__|_|  /\____/ 
     \/    \/      \/       

在resource目錄下新建banner.txt,並將上面內容復制到文件中。最后在resource/application.properties文件中添加以下配置內容:

spring.banner.location=banner.txt

重新啟動服務,即可看到自定義的banner。

關閉banner顯示功能

關閉banner功能,只需要在在啟動類的main方法中加入以下代碼:

    public static void main(String[] args) {
		SpringApplication application = new SpringApplication(DemoApplication.class);
		application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
	}

重啟服務即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM