Results 1 to 4 of 4

Thread: Build URLs with application path part

  1. #1
    Join Date
    Jul 2012
    Posts
    22

    Default Build URLs with application path part

    Hi guys and sorry for stupid question (can't handle it for an hour yet):

    is there an equivalent for
    <jstl:url value="${myURL}" />
    but for use in controllers? I need an application part too (e. g. URLs like /application/myURL).

    Thanks!

  2. #2
    Join Date
    Jul 2012
    Posts
    22

    Default UrlBuilder

    Hmm. I tried this class. Looks very nice! Source thread here.

    Maybe more "standard" spring methods exist?

  3. #3
    Join Date
    Jan 2007
    Location
    Kuala Lumpur, Malaysia
    Posts
    138

    Default

    I use implements ServletContextAware

    http://static.springsource.org/sprin...textAware.html

    ServletContextAware uses "injection by interface", if you implement this interface, you bean would be injected with the servlet context.

    Once you get the servlet context (you need at least servlet 2.5), you can call "getContextPath".

    http://grepcode.com/file/repo1.maven...xtPath% 28%29

    so:
    1. add a new member variable
    Code:
    private ServletContext servletContext;
    2. implement an interface
    Code:
    public class YourController implements ServletContextAware {
    }
    3. implement the setter method

    4. call
    Code:
    servletContext.getContextPath()
    to get the context path.
    Last edited by titiwangsa; Sep 15th, 2012 at 08:06 AM. Reason: provide more info

  4. #4
    Join Date
    Jul 2012
    Posts
    22

    Default

    titiwangsa, thanks alot for your reply.

    With your solution I've found even simpler method (strange, but it was obvious ) - just use request.getContextPath(). Something like this works perfect (I do not know, however, what is the minimum required version of spring for it):

    Code:
    @RequestMapping(value = "/test")
    public String testProcess(Model model, HttpServletRequest request) {
    
    	String appPath = request.getContextPath();
    	Logger.getLogger(this.getClass()).info("Application path is: " + appPath);
    
    	return "viewName";
    }
    So, to have full equivalent for <jstl:url value="${myURL}" /> we can use this code:

    Code:
    @RequestMapping(value = "/test")
    public String testProcess(Model model, HttpServletRequest request,
    		HttpServletResponse response) {
    
    	String myURL = "/nextTest";
    	String nextTestFullURL = response.encodeURL(request.getContextPath() + myURL);
    
    	... pass to model, if needed ...
    
    	return "viewName";
    }
    Best regards
    Lsync

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •