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