自定义返回状态码

首先新建一个工具类:testResult.java

public class testResult extends HashMap implements Serializable {

	public static final testResult SUCCEED = new testResult(200, "成功");
	public static final testResult Failed = new testResult(0, "失败");

	public testResult(int status, String massage) {
		super();
		this.put("status", status).put("message", massage);
	}

	public testResult put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public static testResult build(int i, String message) {
		return new testResult(i, message);
	}
}

可以看到定义了两个状态,如果有需要可以定义更多

新建一个类testController.java

@Controller
@RequestMapping("/test")
public class testController {

	// 使用日志进行打印接收到的数据
	public Logger logger = LoggerFactory.getLogger(testController.class);

	@RequestMapping(value = "/testform", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public testResult testform(@RequestBody testBean test) {
		try {
			logger.info("获取到数据为:" + test.toString());
			return testResult.SUCCEED;
		} catch (Exception e) {
			return testResult.build(500, e.getMessage());
		}
	}
}

需要返回成功或失败直接return即可

 

 

你可能感兴趣的:(java基础)