Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC handler returns String with extra quotes

Tags:

spring-mvc

I'm using Spring 3.1 and I have a handler that should return a String value. Here's how my handler looks like:

@RequestMapping(value = TEST_HANDLER_PATH, method = RequestMethod.POST)
public ResponseEntity<String> handleTest(HttpServletRequest request,
    @RequestParam("parma1") String param) throws Exception {
    String ret = ...
    ...
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/plain;charset=utf-8");
    return new ResponseEntity<String>(ret, headers, HttpStatus.CREATED);
}

I also tried annotating method with @ResponseBody with return ret; at the end.

In both cases, when I hit the service, I get extra quotes around String value (e.g. "This is a test"). I'm guessing this is due to message conversion. That's why I tried defining Content-Type header, to hit StringHttpMessageConverter explicitly, to no avail.

like image 804
mkvcvc Avatar asked Jan 12 '13 12:01

mkvcvc


1 Answers

Had the same problem.

Just make sure you register a org.springframework.http.converter.StringHttpMessageConverter as well as your Jackson one so that Strings are treated literally and not attempted to be converted to JSON (with extra quotes).

Just instantiate with default constructor or constructor with your preferred Charset. The media types should be set for you with the standard internal defaults. If you're configuring via code extending WebMvcConfigurerAdapter then you just add the converters in the configureMessageConverters(List<HttpMessageConverter<?>> converters) method.

like image 184
Matt Byrne Avatar answered Oct 04 '22 23:10

Matt Byrne