【问题标题】:Can Spring MVC controller set the URL to be shown in browser?Spring MVC 控制器可以设置要在浏览器中显示的 URL 吗?
【发布时间】:2016-04-15 14:48:23
【问题描述】:

我们有一个 Spring MVC 控制器方法,它为 url 模式 /hello/{userName} 提供服务。

@RequestMapping("/hello/{userName}")  
    public ModelAndView helloWorld(@PathVariable("userName") String productId) {  
        String message = "HELLO"+userName;  
        return new ModelAndView("hellopage", "message", message);  
    }  

这里当我们请求 /hello/Tom 时,hellopage.html 将在浏览器中使用 URL http://localhost:8080/myApp/hello/Tom 进行服务

我们需要 URL 为 http://localhost:8080/myApp/Tom。有什么方法可以设置从控制器返回时在浏览器中显示的 URL。

【问题讨论】:

    标签: spring-mvc url-mapping


    【解决方案1】:

    当然,您可以使用redirect 做到这一点。编写两个控制器:

    @RequestMapping("/hello/{userName}")  
    public string helloWorld(@PathVariable("userName") String userName, Model model) {  
        String message = "HELLO" + userName;  
        model.addAttribute("message", message);
        return "redirect:" + userName;
    }  
    
    @RequestMapping("/{userName}")  
    public ModelAndView userHello((@ModelAttribute("message") String message)) {    
        return new ModelAndView("hellopage", "message", message);  
    }  
    

    【讨论】:

    • 感谢您的回答。但是已经有一个带有“/{myString}”的控制器提供不同的功能。所以我不能再次使用“/{userName}”。我的意图是显示 URL 的更简洁/更简单,尽管它们有很长的请求映射。
    • 当然映射到“/{userName}”是不合适的。就像你说的那样,这是一个你通常可以用来实现这个目的的例子。
    【解决方案2】:

    我认为您也可以为此使用 tukey url-rewrite:http://tuckey.org/urlrewrite/

    这通过使用过滤器允许 Tomcat 中的 Apache mod_rewrite 功能,您不必为所有内容编写两个控制器。

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      • 2020-02-12
      相关资源
      最近更新 更多