@RequestMapping("/admin")
public String index(ModelMap modelMap,HttpServletRequest req){
String scheme = req.getScheme();
String serverName = req.getServerName();
int serverPort = req.getServerPort();
String path = req.getContextPath();
String basePath = scheme+"://"+serverName+":"+serverPort+path+"/";
modelMap.put("basePath",basePath);
modelMap.put("adminPath", basePath+"admin/");
modelMap.put("staticPath", basePath+"static/admin/common");
return "admin/index";
}
@RequestMapping("/admin/login")
public String login(ModelMap modelMap,HttpServletRequest req){
String scheme = req.getScheme();
String serverName = req.getServerName();
int serverPort = req.getServerPort();
String path = req.getContextPath();
String basePath = scheme+"://"+serverName+":"+serverPort+path+"/";
modelMap.put("basePath",basePath);
modelMap.put("adminPath", basePath+"admin/");
modelMap.put("staticPath", basePath+"static/admin/common");
return "admin/login";
}
I wrote two copies of the code to obtain the path. It feels so bloated. How can I write only one copy and then share it?
迷茫2017-06-12 09:21:12
1. First of all, if you don’t understand the concept of middleware, you can’t use it indiscriminately
2. Back to your question, it is a scenario of method extraction. It is recommended to read the book <<Code Refactoring>>
高洛峰2017-06-12 09:21:12
The code will look much better if you just refactor it
public String index(ModelMap modelMap,HttpServletRequest req){
String basePath = getBasePath(req);
modelMap.put("basePath",basePath);
modelMap.put("adminPath", basePath+"admin/");
modelMap.put("staticPath", basePath+"static/admin/common");
return "admin/index";
}
private String getBasePath(HttpServletRequest req) {
String scheme = req.getScheme();
String serverName = req.getServerName();
int serverPort = req.getServerPort();
String path = req.getContextPath();
String basePath = scheme+"://"+serverName+":"+serverPort+path+"/";
return basePath;
}