Spring Boot(一)指定Http響應狀態碼


在基於Spring Boot的開發過程中有時候我們需要返回一個指定的Http響應狀態碼,比如500錯誤,這時就需要用到ResponseEntity。下面是完整的例子:

1、修改pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.ralgond</groupId>
	<artifactId>boot-customizable-httpcode</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>

	</build>

</project>

2、增加主啟動類

package com.github.raglond.custhttpcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
public class CustHttpCodeApp {

	@RequestMapping(method=RequestMethod.GET, value="/testA")
	public String testA() {
		return "...testA";
	}

	@RequestMapping(method=RequestMethod.GET, value="/testB")
	public ResponseEntity<String> testB() {
		return new ResponseEntity<String>("...testB", HttpStatus.INTERNAL_SERVER_ERROR);
	}
	
	static class UserInfo {
		public String name;
		public String address;
		
		public UserInfo(String name, String address) {
			this.name = name;
			this.address = address;
		}
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/testC")
	public ResponseEntity<UserInfo> testC() {
		return new ResponseEntity<UserInfo>(new UserInfo("abc", "addr"), HttpStatus.INTERNAL_SERVER_ERROR);
	}
	
	public static void main(String args[]) {
		SpringApplication.run(CustHttpCodeApp.class, args);
	}
}

3、運行

啟動主啟動類,並在瀏覽器里輸入http://localhost:8080/testC,可以得到結果:

{"name":"abc","address":"addr"}

並且此次響應的Http狀態碼為500,如下圖:


免責聲明!

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



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