使用Spring MVC的应用程序路由

cla*_*ivp 11 java design-patterns spring-mvc url-routing

我正在寻找一种方法来管理我的WebApp上的路由使用.基本上,我有三个可以共享路由器模式的地方.我可以通过表达语言发送这个模式用于我的观点.

@Controller
public class LoginRuasController
{
    @RequestMapping("/system/index")
    public String logout(ModelMap model, HttpSession session)
    {
        return "system/index";
    }   

    @RequestMapping("/system/logout")
    public String logout(ModelMap model, HttpSession session)
    {
        session.setAttribute("xxx", null);
        return "redirect:/system/login";
    }
}
Run Code Online (Sandbox Code Playgroud)

图案:

/system/index
system/index
redirect:/system/login
Run Code Online (Sandbox Code Playgroud)

观点:

<a href="#{Routes.newuser}">Triple X</a>
Run Code Online (Sandbox Code Playgroud)

最初,RequestMapping请求一个常量值,因此这会产生一个问题,以实现具有静态返回的Route类.有没有解决方案?

cla*_*ivp 9

我找到了一个解决方案,如下:

1)我创建了一个Routes类

public class Routes {

    private static HashMap<String, String> routes;

    public static final String host = "/mywebapp";
    public static final String home = "/home";
    public static final String login = "/login";
    public static final String logout = "/logout";

    private static void setRoutes()
    {       
        if(routes == null)
        {
            routes = new HashMap<String, String>();

            routes.put("host", host);
            routes.put("home", host + home);
            routes.put("entrar", host + entrar);
            routes.put("sair", host + sair);
        }
    }   

    public static HashMap<String, String> getRoutes()
    {
        setRoutes();

        return routes;
    }

    public static String getRoute(String destin)
    {
        setRoutes();

        return routes.get(destin);
    }

}
Run Code Online (Sandbox Code Playgroud)

2)我在我的控制器上使用...现在可以设置RequestMapping

@Controller
public class HomeController extends AbstractController {

    @RequestMapping(Routes.home)
    public String home(ModelMap model)
    {
        preRender(model);       
        return Routes.home;
    }

}
Run Code Online (Sandbox Code Playgroud)

3)我设置Routes用于我的视图

public abstract class AbstractController {

    protected void preRender(ModelMap model) {
        model.addAttribute("routes", Routes.getRoutes()); 
    }

}
Run Code Online (Sandbox Code Playgroud)

4)它现在可用于视图

<body>
    <p>Mary is singing.</p>
    <p><a href="${routes.home}">Home</a></p>
</body>
Run Code Online (Sandbox Code Playgroud)

  • 老问题,我知道,但对于未来的搜索者:您还可以使用 `@ControllerAdvice` 和 `@ModelAttribute` 的组合将路由类的引用添加到与每个控制器关联的模型中。 (2认同)
  • 你有一个例子吗? (2认同)

nyl*_*l66 8

在GitHub上查看SpringMVC路由器项目:

https://github.com/resthub/springmvc-router

它是SpringMVC的play的路由文件的实现