java - How to use UriComponentsBuilder in non-servlet environment? -


the docs state if i'm not within servlet calling thread, still want make use of uricomponentsbuilder (eg in batch import), use servleturicomponentsbuilder.fromcurrentcontextpath().

@see https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-uri-building

i tried follows docs:

public string createurl() {     uricomponentsbuilder base = servleturicomponentsbuilder.fromcurrentcontextpath().path("/en");     mvcuricomponentsbuilder builder = mvcuricomponentsbuilder.relativeto(base);     builder.withmethodcall(on(bookingcontroller.class).getbooking(21)).buildandexpand(42);      uri uri = uricomponents.encode().touri();     return uri.tostring(); } 

for testing non-servlet call:

@postconstruct public void init() {     builder.createurl(); } 

but getting exception:

caused by: java.lang.illegalstateexception: not find current request via requestcontextholder     @ org.springframework.util.assert.state(assert.java:392) ~[spring-core-4.3.4.release.jar:4.3.4.release]     @ org.springframework.web.servlet.support.servleturicomponentsbuilder.getcurrentrequest(servleturicomponentsbuilder.java:190) ~[spring-webmvc-4.3.4.release.jar:4.3.4.release]     @ org.springframework.web.servlet.support.servleturicomponentsbuilder.fromcurrentcontextpath(servleturicomponentsbuilder.java:158) ~[spring-webmvc-4.3.4.release.jar:4.3.4.release] 

so might wrong here?

the documentation mentioned stated static methods use in servlet environment:

in servlet environment servleturicomponentsbuilder sub-class provides static factory methods [...]

so if you're not in said servlet environment, need use plain uricomponentsbuilder:

uricomponentsbuilder.newinstance().scheme("http").host("example.com") 

which fit code

public string createurl() {     uricomponentsbuilder base = uricomponentsbuilder.newinstance().scheme("http").host("example.com").path("/en");     mvcuricomponentsbuilder builder = mvcuricomponentsbuilder.relativeto(base);     builder.withmethodcall(on(bookingcontroller.class).getbooking(21)).buildandexpand(42);      uri uri = uricomponents.encode().touri();     return uri.tostring(); } 

the reason behind in servlet environment can access scheme , host , context path querying servlet / servletcontext , on. running outside of webapp, information (scheme, host, context path) need come someplace else.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -