java - How does SpringMVC have such things as middleware?
ringa_lee
ringa_lee 2017-06-12 09:19:12
0
3
636
@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_lee
ringa_lee

ringa_lee

reply all(3)
迷茫

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

阿神

Write it into filter, or use dynamic proxy

小葫芦

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!