java - SpringMVC如何有没有中间件之类的东西 ?
ringa_lee
ringa_lee 2017-06-12 09:19:12
0
3
677
@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";
    }

获取路径的代码写了两份 ,感觉好臃肿啊,怎么让只写一份,然后给共用?

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
迷茫

1.首先中间件概念你没弄清楚,不能乱用
2.回到你的问题,就是一个方法抽取的场景,建议看一下<<代码重构>>这本书

阿神

写到filter当中,或者用动态代理

小葫芦

代码随便重构一下就好看多了

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;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板