Maison  >  Questions et réponses  >  le corps du texte

java - Comment SpringMVC propose-t-il des éléments tels qu'un middleware?

@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_leeringa_lee2686 Il y a quelques jours640

répondre à tous(3)je répondrai

  • 迷茫

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

    répondre
    0
  • 阿神

    阿神2017-06-12 09:21:12

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

    répondre
    0
  • 高洛峰

    高洛峰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;
    }

    répondre
    0
  • Annulerrépondre