java - SpringMVC如何有沒有中間件之類的東西 ?
ringa_lee
ringa_lee 2017-06-12 09:19:12
0
3
681
@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;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板