Spring MVC绑定到同一个@RequestMapping

时间:2013-01-21 06:17:35

标签: spring java-ee spring-mvc

假设我们有此登录代码和&我们想要的是,如果凭证是针对管理页面的,则RequestMapping是针对admin&如果是用户凭证,则用户重定向到用户面板。 现在,两者的主页都反对我在下面的代码中定义的相同URL,如:

http://localhost:8080/project/{username}/main

我的问题是:

如果在Controller类中完成登录检查后它们具有相同的RequestMapping“main”,我们如何将这两个方法分开?

@RequestMapping(value = "/login")
public String welcome(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpSession session, Model model) throws RemoteException, NotBoundException {

    int checkAccount = uiClient.checkAdminAccount(username, password);
    if (checkAccount == 1) {
        session.setAttribute("username", username);
        return "redirect:/" + username + "/main";
    } else if (checkAccount == 0) {
        checkAccount = uiClient.checkAccount(username, password);
        if (checkAccount == 1) {
            session.setAttribute("username", username);
            return "redirect:/" + username + "/main";
        } else if (checkAccount == 0) {
            return "login";
        }
    } else {
        return "databaseError";
    }
    return "login";
}

@RequestMapping(value = "/{username}/main")
public String indexPage(@PathVariable("username") String username) {
    return "/user/userPanel";
}

@RequestMapping(value = "{username}/main")
public String adminIndexPage(@PathVariable("username") String username){
    return "/admin/adminPanel";
}

我的意思是,有没有像我们可以为每个Mapping& amp;在登录过程完成后将它们分开,以便管理员重定向到adminPanel&用户还重定向到userPanel,但两者都使用相同的URL:

http://localhost:8080/project/{username}/main

???

1 个答案:

答案 0 :(得分:1)

这样:

@RequestMapping(value = "/login")
public String welcome(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpSession session, Model model) throws RemoteException, NotBoundException {

    int checkAccount = uiClient.checkAdminAccount(username, password);
    if (checkAccount == 1) {
        session.setAttribute("username", username);
        session.setAttribute("userrole", "Admin");
        return "redirect:/" + username + "/main";
    } else if (checkAccount == 0) {
        checkAccount = uiClient.checkAccount(username, password);
        if (checkAccount == 1) {
            session.setAttribute("username", username);
            session.setAttribute("userrole", "Admin");
            return "redirect:/" + username + "/main";
        } else if (checkAccount == 0) {
            return "login";
        }
    } else {
        return "databaseError";
    }
    return "login";
}

@RequestMapping(value = "/{username}/main")
public String indexPage(@PathVariable("username") String username) {
    if ("Admin".equals(session.getAttribute("userrole"))) {
        return "/admin/adminPanel";
    } else {
        return "/user/userPanel";
    }
}

为简单起见,我没有使用Spring Security来检查用户角色。