Maison > Questions et réponses > le corps du texte
@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";
}
J'ai écrit deux copies du code pour obtenir le chemin. Cela semble tellement gonflé. Comment puis-je n'écrire qu'une seule copie et ensuite la partager ?
迷茫2017-06-12 09:21:12
1. Tout d'abord, si vous ne comprenez pas le concept de middleware, vous ne pouvez pas l'utiliser sans discernement
2. Revenons à votre question, il s'agit d'un scénario d'extraction de méthode. <Refactorisation du code>>
高洛峰2017-06-12 09:21:12
Le code sera bien meilleur si vous le refactorisez simplement
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;
}