从controller到数据的获取

本文详细阐述了从Controller层如何调用Service层,再由Service层操作DAO层,最终获取并返回所需数据的整个过程,同时提及了状态码在其中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

controller中的代码

@Controller
@RequestMapping("/brand")
public class PmsBrandController {
	@Autowired
	private PmsBrandService demoService;
	
	@RequestMapping(value="/create",method=RequestMethod.POST)
	@ResponseBody
	public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
		CommonResult commonResult;
		int count = demoService.createBrand(pmsBrand);
		if(count == 1) {
			commonResult = CommonResult.success(pmsBrand);
		}else{
			commonResult = CommonResult.failed("操作失败");
		}
		return commonResult;
	}
}

service层

@Service
public class PmsBrandService {
	@Autowired
	private PmsBrandMapper brandMapper;
	
	public int createBrand(PmsBrand brand){
		return brandMapper.insertSelective(brand);
	}
}

dao层

public interface PmsBrandMapper{
		int insertSelective(PmsBrand record);
}

要返回的数据

/**
 *通用返回对象
 */
 @Setter
 @Getter
public class CommonResult<T>{
	private long code;
	private String message;
	private T data;
	
	protected CommonResult() {
	}
	protected CommonResult(long code,String message,T data){
		this.code = code;
		this.message = message;
		this.data = data;
	}
	//返回成功结果 
	public static <T> CommonResult<T> success(T data){
		return new CommonResult<T>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMethod,data);
	}
	
	//成功返回结果
	public static <T> CommonResult<T> success(T data,String message){
		return new CommonResult<T>(ResultCode.SUCCESS.getCode(),message,data);
	}
	//返回失败结果
	public static <T> CommonResult<T> failed(String message){
		return new CommonResult<T>(ResultCode.FAILED.getCode(),message,null);
	}
	.......
}

状态码

public enum ResultCode{
	SUCCESS(200,"操作成功"),
	FAILE(500,"操作失败");
	private long code;
	private String message;
	private ResultCode(long code,String message) {
		this.code = code;
		this.message = message;
	}
	public long getCode(){
		return code;
	}
	public String getMessage(){
		return message;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值