【问题标题】:Set the base URL in the page when using Spring MVC 3使用 Spring MVC 3 时在页面中设置基本 URL
【发布时间】:2011-12-10 23:31:27
【问题描述】:

我现在正在学习 Spring MVC 3。

在我的页面中设置 URL 时遇到一些问题,因为页面中的 URL 是相对于当前页面的,所以我想在每个页面中设置基本 URL。

当我使用 Structs 2 时,我会像这样创建一个 BaseAction:

public class BaseAction{
  public BaseAction(){
     string baseURL=getServletContext.getHost()+"...."+.....;
  }
  public getBaseURL(){xxxxx}
}

然后在页面中:

<base href='<s:prototype value="baseURL"/>' /> 

现在,在Spring MVC 3中,由于没有为每个请求创建一个新的相关控制器实例,所以我不知道如何制作?

最后,我觉得我可以使用拦截器了,所以我创建了一个拦截器:

public class BaseURLInterceptor extends HandlerInterceptorAdapter{

    public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler)
        throws Exception {
        return true;
    }

    //after the handler is executed
    public void postHandle(
        HttpServletRequest request, HttpServletResponse response, 
        Object handler, ModelAndView modelAndView)
        throws Exception {
        modelAndView.getModel().setObject("baseURL",requset.getHost()+"......");
    }

}

在页面中:

我可以使用:

<base href="${baseURL}" />

它可以工作,但是当视图被重定向时,它会将此值添加到 URL。

例如:

@Controller
@RequsetMapping("/user")
public class UserController{

    @RequsetMapping("edit/{userid}")
    public String edit(@PathVariable String uid)
        //edit logic
        return "redirect:list"
    }

    @RequsetMapping("list")
    public String list(){
        //get users list
        return "user_list"
    }
}

当我在用户编辑页面制作提交按钮时,我将重定向到:

http://localhost:8080/app/user/list?baseURL=http://localhost:8080

url中的参数?baseURL=http://localhost:8080不是我想要的。

如何解决?

或者使用 Spring MVC 3 解决 URL 路径的更好方法是什么?

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    我可能不正确理解这个问题,但如果你想在 jsp 中为某些链接提供基本 URL,那么你的方法是错误的。

    通常你会做这样的事情:

    测试

    对于控制器中的重定向,如果您使用 RedirectView 而不是返回字符串“redirect:xxx”,您可以指定如何解释 url:重定向视图构造函数 RedirectView(String url, boolean contextRelative) 可用于指定上下文相关到当前的 ServletContext 或相对于 Web 服务器。

    【讨论】:

      【解决方案2】:

      如果我正确理解了问题,这就是您要查找的内容&lt;base href="&lt;c:url value="${webappRoot}" /&gt;

      【讨论】:

      • ${webapprRoot} 的值为空
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 2018-10-10
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多