Spring MVC:在另一个控制器中自动装配控制器

时间:2016-05-25 06:31:58

标签: java spring spring-mvc

我有两个控制器LoginViewControllerUserViewController

@Controller
public class LoginViewController {

    @Autowired
    private UserViewController userViewController;  //Can't autowire, since spring creates a proxy for UserViewController class

    @RequestMapping(value="/login", method=POST)
    public String login(){

        //username and password checking etc

        if(login_successfull){
            //When login successfull, i need to redirect the screen to user dashboard  
            model.addAttribute("loginMessage", "You are loggined successfully")
            return userViewController.viewDashboard(userId);
        }   
    }
}

@Controller
@RequestMapping("/user")
public class UserViewController {

    @Autowired 
    private UserService userService;

    @RequestMapping(value="/dashboard", method=GET)
    public String viewDashboard(Model model, @RequestParam(value="id", required=true) Long userId){
        //Fetch and send user details to dashboard
        model.addAttribute("user", userService.get(userId));
        return "userDashboard"; 
    }
}

用户登录成功后,我需要使用登录成功消息将屏幕重定向到用户仪表板。

为此可以使用2种方法

  1. 由于我有一种方法可以在UserViewController中加载用户信息中心,因此我在UserViewController中自动LoginViewController,导致NoSuchBeanDefinitionException,因为spring创建了一个代理UserViewController

  2. 我可以使用redirect/forward作为返回"redirect:/user/dashboard?id=123"路由到用户信息中心。但是当我更改viewDashboard()方法的网址时,我需要识别并更正所有redirect/forward语句。

  3. 那么,有没有办法从UserViewController.viewDashboard()调用LoginViewController? 我使用的是春季3.1.4和百里香叶

1 个答案:

答案 0 :(得分:4)

如果您希望控制器的输出将用户发送到另一个控制器,您可以执行'重定向':

if(login_successfull){
    //When login successfull, i need to redirect the screen to user dashboard  
    model.addAttribute("loginMessage", "You are loggined successfully")
    return "redirect:/user/dashboard";
}

如果您决定更改控制器的网址,则需要替换网站中的所有HTML链接。如果您已经在进行全局搜索/替换,那么您也应该能够找到重定向实例。

或者,你可以试试这个:

public class UrlConstants {
    public static final String USER_PATH = "/user";
    public static final String DASHBOARD_PATH = "/dashboard";
}

然后你改变你的控制器:

@Controller
@RequestMapping(UrlConstants.USER_PATH)
public class UserViewController {
    ...
    @RequestMapping(value=UrlConstants.DASHBOARD_PATH, method=GET)

然后为你的重定向:

return "redirect:" + UrlConstants.USER_PATH + UrlConstants.DASHBOARD_PATH;