在控制器spring3中重定向

mjg*_*irl 6 spring spring-mvc

在Spring 3中,您可以像这样简单地映射URL:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return "index";
}
Run Code Online (Sandbox Code Playgroud)

是否有可能使这种方法有点重定向到另一个URL,如:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return "second.html";
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
//put some staff in model
    return "second";
}
Run Code Online (Sandbox Code Playgroud)

ska*_*man 15

您不需要重定向 - 只需调用方法:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return second(model);
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
    //put some staff in model
    return "second";
}
Run Code Online (Sandbox Code Playgroud)

这是注释风格的好处之一; 你可以将你的方法链接在一起.

如果您真的想要重定向,那么您可以将其作为视图返回:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public View index(Model model)  {
    return new RedirectView("second.html");
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
    //put some staff in model
    return "second";
}
Run Code Online (Sandbox Code Playgroud)


Rit*_*esh 6

是的重定向将起作用.在索引方法中,将最后一行更改为return "redirect:/second.html" ;

需要编辑 上下文路径和控制器映射.如果DispatcherServlet映射到/ ABC并且控制器的请求映射是/ XYZ,那么您将必须写:
return "redirect:/ABC/XYZ/second.html";