Java的新项目学成在线笔记-day4(二)

本文详细介绍了基于Spring Boot的CMS配置管理系统的接口设计,包括DAO、Service、Controller层的实现,以及使用Postman进行接口测试的过程。同时,演示了如何通过RestTemplate结合OkHttpClient实现远程HTTP请求。

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

3.2.1.3 Dao
定义CmsConfig的dao接口:


public interface CmsConfigRepository extends MongoRepository<CmsConfig,String> { }

3.2.1.4 Service
定义CmsConfigService实现根据id查询CmsConfig信息。

@Service public class CmsConfigService {  
  @Autowired   
  CmsConfigRepository cmsConfigRepository; 
    //根据id查询配置管理信息    
 public CmsConfig getConfigById(String id){   
     Optional<CmsConfig> optional = cmsConfigRepository.findById(id);    
     if(optional.isPresent()){        
    CmsConfig cmsConfig = optional.get();        
     return cmsConfig;       
  }      
  return null;   
  }
 }

3.2.1.5 Controller

@RestController @RequestMapping("/cms/config")
public class CmsConfigController implements CmsConfigControllerApi {
     @Autowired   
  CmsConfigService cmsConfigService;   
    @Override   
  @GetMapping("/getmodel/{id}")  
  public CmsConfig getmodel(@PathVariable("id") String id) { 
       return cmsConfigService.getConfigById(id); 
    }
 }

3.2.1.6 测试
使用postman测试接口: get请求:http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f (轮播图信息)
3.2.3 远程请求接口
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的 请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,本项目使用OkHttpClient完成http请求, 原因也是因为它的性能比较出众。
1、添加依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
</dependency>

2、配置RestTemplate
在SpringBoot启动类中配置 RestTemplate


... public class ManageCmsApplication { 
   public static void main(String[] args) { 
       SpringApplication.run(ManageCmsApplication.class,args); 
    }    
  @Bean 
    public RestTemplate restTemplate() {  
      return new RestTemplate(new OkHttp3ClientHttpRequestFactory());   
  }
}

3、测试RestTemplate
根据url获取数据,并转为map格式。

@Test public void testRestTemplate(){ 
   ResponseEntity<Map> forEntity =
 restTemplate.getForEntity("http://localhost:31001/cms/config/get/5a791725dd573c3574ee333f",  Map.class); 
    System.out.println(forEntity); 
}

转载于:https://blog.51cto.com/13517854/2340049

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值