简体   繁体   English

Spring Web 服务删除响应字符串中的多个空格

[英]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".使用 URL localhost:8080/hello?name=Test 观察响应为“Hello Test”。 Issue here is in the String Name i have trailing spaces next to Hello.这里的问题是在字符串名称中,我在 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.非破坏性规范不会在 html 中折叠,而空间会。

Of course in any real api, you wouldn't want to return html characters.当然,在任何真正的 api 中,您都不想返回 html 字符。 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.浏览器将其显示为 HTML 格式并剪切空格。 To test it create a text file with String "Hello Test" and save it as Test.html file and open it in the browser.要测试它,请创建一个带有字符串“Hello Test”的文本文件并将其保存为 Test.html 文件并在浏览器中打开它。 The browser will display it as "Hello Test".浏览器将其显示为“Hello Test”。 As @Athanasios Kataras pointed out you need to replace space character with " ".正如@Athanasios Kataras 指出的那样,您需要用“”替换空格字符。 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.为了让您的生活更轻松,有一个名为 MgntUtils(由我编写)的开源库,它提供了一个实用程序,可以转换字符串以保留 Html 的缩进。 In simple words, it replaces " " with " " and "\\n" with "简单来说,它将“”替换为“”,将“\\n”替换为“
". 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该库可在此处作为 Maven 工件获得,在 Github 上可此处获得,Javadoc 可在此处获得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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