java controller getMapping 使用策略模式代替if-else返回页面并携带model参数
时间: 2023-05-21 19:04:00 浏览: 71
可以使用策略模式来代替if-else语句,实现更加灵活的页面返回和model参数携带。具体实现可以参考以下代码:
1. 定义一个接口,用于实现不同的策略:
```
public interface PageStrategy {
String getPage(Model model);
}
```
2. 实现不同的策略类:
```
public class HomePageStrategy implements PageStrategy {
@Override
public String getPage(Model model) {
// 返回首页页面
return "home";
}
}
public class AboutPageStrategy implements PageStrategy {
@Override
public String getPage(Model model) {
// 返回关于页面
return "about";
}
}
// 其它策略类...
```
3. 在Controller中使用策略模式:
```
@Controller
public class MyController {
private Map<String, PageStrategy> strategyMap = new HashMap<>();
public MyController() {
// 初始化策略Map
strategyMap.put("home", new HomePageStrategy());
strategyMap.put("about", new AboutPageStrategy());
// 其它策略...
}
@GetMapping("/{page}")
public String getPage(@PathVariable String page, Model model) {
// 根据页面名称获取对应的策略
PageStrategy strategy = strategyMap.get(page);
if (strategy == null) {
// 如果没有对应的策略,返回错误页面
return "error";
}
// 调用策略的getPage方法,返回对应的页面
return strategy.getPage(model);
}
}
```
这样,就可以通过不同的策略来返回不同的页面,并且可以携带不同的model参数。