gpt4 book ai didi

java - 在运行时创建@RestController

转载 作者:行者123 更新时间:2023-11-30 06:30:02 25 4
gpt4 key购买 nike

我在使用 REST 服务器和 REST 客户端的应用程序中使用 Spring Boot。当我让人们选择 URL 映射时,就会出现问题,因为那时我需要使用此 URL 映射动态创建 REST Controller :

@SpringBootApplication
public static void main(String[] args){
SpringApplication.run(MyClass.class);
String urlMapping = "/url/url";
CreateNewRestController c = new CreateNewRestController(urlMapping);
}

@RestController
public class CreateNewRestController{
String url;
public CreateNewRestController(String url){
this.url = url
}

@RequestMapping(value = this.url,method = RequestMethod.GET)
public String getHello(){
return "Hello";
}
}

“当您可以在 RequestMapping 中使用常量字符串时,为什么还要使用 url 变量?”你可能会问。但这是一个简单的示例,我需要使用变量参数创建 RequestMapping。

最佳答案

Github link - here

我找到了我的问题的答案,也许是实时使用 RequestMapping 的解决方案。我创建了一个 RestController,它接受所有 HTTP 请求,请求请求 HashMap ,其中包含 uri 映射(如键)和类 Controller (如值)。

通用 Controller :

@RestController
public class GeneralController {

HashMap<String,PersonalizedController> petitions = new HashMap<String,PersonalizedController>();

@RequestMapping("**")
public ResponseEntity<Object> index(HttpServletRequest request,HttpServletResponse response,@RequestBody Object body) {

// Inicialization zone - this zone don't must exist
petitions.put("/dir/esta1", new PersonalizedController("esta1"));
petitions.put("/dir/esta2", new PersonalizedController("esta2"));
//-------------------------------------------------

return handlePetition(request,response);
}

private ResponseEntity<Object> handlePetition(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String petition = request.getRequestURI();
String method = request.getMethod();

return petitions.get(petition).makePetition(method,new String());
}
}

Controller 类:

public class PersonalizedController {

private String name;

public PersonalizedController(String name) {
this.name = name;
}

public ResponseEntity<Object> makePetition(String method,Object body) {
// TODO Auto-generated method stub
switch (method) {
case "GET":
return doGet(body);
case "POST":
return doPost(body);
case "PUT":
return doPut(body);
case "DELETE":
return doDelete(body);
default:
return new ResponseEntity<Object>("",HttpStatus.METHOD_NOT_ALLOWED);
}
}

public ResponseEntity<Object> doGet(Object body) {
return new ResponseEntity<Object>("["+name+"] GET",HttpStatus.OK);
}

public ResponseEntity<Object> doPost(Object body) {
return new ResponseEntity<Object>("["+name+"] POST",HttpStatus.OK);
}

public ResponseEntity<Object> doDelete(Object body) {
return new ResponseEntity<Object>("["+name+"] DELETE",HttpStatus.OK);
}

public ResponseEntity<Object> doPut(Object body) {
return new ResponseEntity<Object>("["+name+"] PUT",HttpStatus.OK);
}

}

关于java - 在运行时创建@RestController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com