hguser
hguser

Reputation: 36028

Set the base URL in the page when using Spring MVC 3

I am learning the Spring MVC 3 now.

I meet some problems when set the URLs in my page, since the URL in the page are relatived to the current page, so I want to set the base URL in each page.

When I use Structs 2, I create a BaseAction like this:

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

Then in the page:

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

Now, in Spring MVC 3, since the a new instance of related controller is not created for each request, so I do not know how to make it?

Finally, I think I can use the interceptor, so I create a interceptor:

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()+"......");
    }

}

In the page:

I can use :

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

It works, however when a view is redirected, it will add this value to the URL.

For example:

@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"
    }
}

When I make the submit button in the user edit page, I will redirect to :

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

Where the parameter in the url ?baseURL=http://localhost:8080 is not what I want.

How to fix it?

Or what is the better way to solve the URL path using Spring MVC 3?

Upvotes: 1

Views: 4982

Answers (2)

ant
ant

Reputation: 22948

If I understand the problem correctly this is what you're looking for <base href="<c:url value="${webappRoot}" />

Upvotes: 0

Ralph
Ralph

Reputation: 120781

May I do not correct understand the problem, but if you want to have the base url in the jsp for some links than your approach is the wrong one.

normaly you would do something like this:

test

And for redirects in the controller you can specify how the url has to be interpreted if you use RedirectView instead of returning the String "redirect:xxx": the redirect view constructor RedirectView(String url, boolean contextRelative) can be used to specify context relative to the current ServletContext or relative to the web server.

Upvotes: 0

Related Questions