/** * 服务对象 */ @Resource private TblSmtzInfoService tblSmtzInfoService; //校验header @Value("${interfaceHeader.FskAppKey}") private String FskAppKey; @Value("${interfaceHeader.FskAppSecret}") private String FskAppSecret; @Value("${interfaceHeader.YjAppKey}") private String YjAppKey; @Value("${interfaceHeader.YjAppSecret}") private String YjAppSecret; /** * 新增数据 * * @param tblSmtzInfo 实体对象 * @return 新增结果 */ @PostMapping("addList") public AjaxResult addList(@RequestBody List<TblSmtzInfo> tblSmtzInfo, HttpServletRequest request) { if (FskAppKey.equals(request.getHeader("appKey")) && FskAppSecret.equals(request.getHeader("appSecret"))) { for (TblSmtzInfo t : tblSmtzInfo) { t.setCreatedTime(new DateTime()); } return AjaxResult.success(this.tblSmtzInfoService.saveBatch(tblSmtzInfo)); } else { return AjaxResult.error(); } }代码优化
时间: 2024-02-14 21:15:16 浏览: 64
可以考虑将 interfaceHeader 中的 appKey 和 appSecret 提取出来,放到一个配置类中进行配置,避免在代码中硬编码,提高代码的可维护性和可扩展性。同时,可以将校验 appKey 和 appSecret 的逻辑封装为一个方法,以提高代码的可读性和复用性。代码优化后的示例:
在配置类中配置 appKey 和 appSecret:
```
@Configuration
public class InterfaceHeaderConfig {
@Value("${interfaceHeader.FskAppKey}")
private String fskAppKey;
@Value("${interfaceHeader.FskAppSecret}")
private String fskAppSecret;
@Value("${interfaceHeader.YjAppKey}")
private String yjAppKey;
@Value("${interfaceHeader.YjAppSecret}")
private String yjAppSecret;
@Bean
public InterfaceHeader interfaceHeader() {
return new InterfaceHeader(fskAppKey, fskAppSecret, yjAppKey, yjAppSecret);
}
}
public class InterfaceHeader {
private String fskAppKey;
private String fskAppSecret;
private String yjAppKey;
private String yjAppSecret;
public InterfaceHeader(String fskAppKey, String fskAppSecret, String yjAppKey, String yjAppSecret) {
this.fskAppKey = fskAppKey;
this.fskAppSecret = fskAppSecret;
this.yjAppKey = yjAppKey;
this.yjAppSecret = yjAppSecret;
}
public boolean isValid(HttpServletRequest request) {
String appKey = request.getHeader("appKey");
String appSecret = request.getHeader("appSecret");
return (fskAppKey.equals(appKey) && fskAppSecret.equals(appSecret)) || (yjAppKey.equals(appKey) && yjAppSecret.equals(appSecret));
}
}
```
在控制器中调用 InterfaceHeader 进行校验:
```
@RestController
@RequestMapping("/tblSmtzInfo")
public class TblSmtzInfoController {
@Resource
private TblSmtzInfoService tblSmtzInfoService;
@Autowired
private InterfaceHeader interfaceHeader;
@PostMapping("addList")
public AjaxResult addList(@RequestBody List<TblSmtzInfo> tblSmtzInfo, HttpServletRequest request) {
if (interfaceHeader.isValid(request)) {
for (TblSmtzInfo t : tblSmtzInfo) {
t.setCreatedTime(new DateTime());
}
return AjaxResult.success(this.tblSmtzInfoService.saveBatch(tblSmtzInfo));
} else {
return AjaxResult.error();
}
}
}
```
阅读全文