search

Home  >  Q&A  >  body text

java - How does SpringMVC have such things as 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";
    }

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?

ringa_leeringa_lee2791 days ago701

reply all(3)I'll reply

  • 迷茫

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

    reply
    0
  • 阿神

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

    Write it into filter, or use dynamic proxy

    reply
    0
  • 高洛峰

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

    reply
    0
  • Cancelreply