java - Comment SpringMVC propose-t-il des éléments tels qu'un middleware?
ringa_lee
ringa_lee 2017-06-12 09:19:12
0
3
635
@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 ?

ringa_lee
ringa_lee

ringa_lee

répondre à tous(3)
迷茫

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>>

阿神

Écrivez-le dans le filtre ou utilisez un proxy dynamique

小葫芦

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;
}
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!