How to handle Plus (+) Sign in HandlerInterceptorAdapter Similar to ClientHttpRequestInterceptor for Every Request - spring

The plus + is taken care as %2B in (ClientHttpRequestInterceptor) '+' (plus sign) not encoded with RestTemplate using String url, but interpreted as ' ' (space)
However i have interceptors which extends HandlerInterceptorAdapter instead of implements ClientHttpRequestInterceptor to handle every request which passes through. Any setter methods to change the URL before it hits the controller.
How to change the value of the URL or do the similar changes via HandlerInterceptorAdapter ?
Thanks

Related

How to capture a common request parameter for all requests in spring BOOT REST

In Jersey Rest API
if any common request parameters are there then we can capture that value at RootResource level using the below code.
#QueryParam("q")
private String qQueryParams
Is there any similar approach in Spring Rest API.
In other words, all my endpoint URL will contain the query parameter "q". How to capture this data at class level instead of every request.
Thanks, Vijay
you can use #RequestMapping({q}/test) above controller and pass #PathVariable String q as method argument.
#Controller
#RequestMapping(value = "{q}/test")
class TestController {
#RequestMapping(value="/abc")
public ModelAndView doSomething(#PathVariable String q) {
// do something with q...
}
}

Spring Boot MVC request mapping overrides static resources

I want to have rest controller in Spring Boot to handle all requests like this: "/{arg}", EXCEPT "/sitemap.xml". How can I achieve that?
You could specify your request mapping on the controller level via regex and exclude some resources (e.g. 'excludeResourceA' and 'excludeResourceB') with:
#RestController
#RequestMapping(value = "/{arg:(?!sitemap.xml|excludeResourceA|excludeResourceB).*$}")
public class YourRestController {
// your implementation
}
Of course you can also specify the request mapping on the method level with the same regex relative to your controller path matching and you can pass the argument with #PathVariable("arg") String arg in your method signature to your method body if you need it.

Get Request fails for .com email addresses because Spring interpretes it as a extensions

(See edit part below 20.08.2015)
I had a similar problem recently (Get request only works with trailing slash (spring REST annotations)) and the solution was to add a regex to the value of #RequestMapping (see also Spring MVC #PathVariable getting truncated).
But now we have realised that the problem still exists, but only for email addresses ending on .com or .org. This is very weird.
Shortly, I use Spring Annotations building a REST Service. I have a GET request with three parameters, the last is an email.
My Controller:
#RequestMapping(method = GET, value = "/{value1}/{value2}/{value3:.+}",
produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public ResponseEntity<MyResponseType> getMyResource(
#ApiParam(value = "...",...)
#PathVariable("value1") String value1,
#ApiParam(value = "...",...)
#PathVariable("value2") String value2,
#ApiParam(value = "...",...)
#PathVariable("value3") String value3) {
//...
}
If I call:
http://myserver:8080/myresource/value1/value2/value3
with value3= email#domain.de / co.uk / .name / .biz /.info, there is no problem at all.
But with certain top level domains (.com, .org so far) I receive Http Status Code 406 (Not accepted).
It works if I add a trailing slash:
http://myserver:8080/myresource/value1/value2/value3/
As we use swagger and swagger does not add trailing slashes, adding a trailing slash is not an option.
What might cause this problem?
I use an ErrorHandler which extends ResponseEntityExceptionHandler.
I debugged it and found that HttpMediaTypeNotAcceptableException ("Could not find acceptable representation") is thrown. But I can't find out yet who is throwing it and why.
edit
I found out that the path http://myserver:8080/myresource/value1/value2/myemail#somewhere.com
is interpreted as file, and "com" is the file extension for the media type "application/x-msdownload", so in Spring's class ProducesRequestCondition.ProduceMediaTypeExpression in the method matchMediaType the line "getMediaType().isCompatibleWith(acceptedMediaType)" fails, because the actually produced media type is "application/json;charset=UTF-8", not "application/x-msdownload".
So the questions changes to: How can I make Spring understand, that .com is not a file extension?
This thread helped me:
SpringMVC: Inconsistent mapping behavior depending on url extension
Obviously this is not a bug but a "feature" and there are two different ways to disable it. I used the annotation version:
#Configuration
#EnableWebMvc
public class RestCommonsMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
I came across this problem when upgraded from spring 3.1.2 to 3.2.7. The answer by Nina helped me (which should be marked as the answer). But instead of extending the WebMvcConfigurerAdapter I did it in my WebConfig that extended WebMvcConfigurationSupport.
#Configuration
public class WebConfig extends WebMvcConfigurationSupport {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
super.configureContentNegotiation(configurer);
configurer.favorPathExtension(false).favorParameter(true);
}
}

Is there an equivalent of a "beforeHandler" for spring 4?

I have a controller with a requestmapping..
#Controller
public class TestController {
private static final String template = "Hello there, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/hello")
public #ResponseBody String hello() {
return "Hello";
}
}
How can I make it such that everytime a user goes to a RequestMapping, or whichever url, some other method is called to println to the console the URL the user is at before it actually enters the method "hello"?
I would like to use this method to ensure users have proper credentials in the future. I see there are #PreAuthorize annotation, but there doesnt seem to be a method associated with it that I can write my own logic, i.e. do a simple println to the console with the current URL the user is at.
You have a number of options.
With Spring, you can implement and register a HandlerInterceptor and implement its preHandle method to log the request URL, which you can reconstruct with the various HttpServletRequest methods.
With pure servlet-api, you can implement and register your own Filter which logs the request URL and then continues the chain, with doFilter(..).
You can also use AOP, advise all your #RequestMapping annotated methods with a #Before advice that logs the URL.

Spring MVC image or character generic controller

I would like to implement a generic controller with one or two methods that react to any GET request. I am trying to simplify this to the point where I can return byte (image etc.) or character based (XML, CSS) without having to map each content type and put a RequestMapping in for each.
The app must be abel to handle any request with any content type.
My dispatcher is currently set to handle all requests via /.
The couple of attempts I have made so far throw ambigious handler errors, or the mapping doesn;t work to the point where text is sent back as byte[] or the other way around.
Has anyone made anything like this work ?
Regards,
Andy
You can have a controller like so
#Controller
public class YourController {
#RequestMapping("/*")
public String doLogic(HttpServletRequest request, HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
out.write(/* some bytes, eg. from an image*/); // write the response yourself
return null; // this is telling spring that this method handled the response itself
}
}
The controller is mapped to every url and every http method. Spring has a set of accepted return types for its handler methods. With String, if you return null, Spring assumes you've handled the response yourself.
As #NilsH commented, you might be better off using a simple servlet for this.

Resources