简体   繁体   中英

Spring web service removes multiple spaces in the response string

As a hobby am learning spring myself. Observing an issue.

Here is the demo rest controller i am using.

@RestController

class DemoHelloService
{

    @GetMapping("/hello")
    public String hello(@RequestParam String name)
    {
        String Name = new String("Hello    "+name);        
        return Name;
    }
}

with URL localhost:8080/hello?name=Test observing response as "Hello Test". Issue here is in the String Name i have trailing spaces next to Hello. but this is not seen in the response from service.

Any help what changes needs to be made to the receive trailing spaces also in the service.

Try this:

String Name = new String("Hello    "+name); 

As you can see here: What's the difference between " "and " "? the non breaking specs does not collapse in html whereas the space does.

Of course in any real api, you wouldn't want to return html characters. It would be better to return the name (in your example it does not apply) and format on the client side.

Your problem is not on the server-side. The return value is fine. The browser when displaying it as HTML formats it and cuts the spaces. To test it create a text file with String "Hello Test" and save it as Test.html file and open it in the browser. The browser will display it as "Hello Test". As @Athanasios Kataras pointed out you need to replace space character with " ". To make your life a bit easier there is an open-source library called MgntUtils (written by me) that provides a utility that converts Strings to preserve indentation for Html. In simple words, it replaces " " with " " and "\\n" with "
". So if you want to use the library, your code would look like:

@GetMapping("/hello")
public String hello(@RequestParam String name)
{
    String Name = TextUtils.formatStringToPreserveIndentationForHtml("Hello    "+name);        
    return Name;
}

The library is available as Maven artifacts here , on Github here , Javadoc is available here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM