如何在 Spring Boot Rest API 中读取包含与号 (&) 的@Request参数属性值



Team,

当我尝试在春季启动休息 api 中读取包含与号 (&( 的请求参数属性值时,我收到数字格式异常。下面是我尝试过的示例代码。请就此建议我。

请求网址:http://loacalhost:8080/search/ad?skey="uc"&fn="M&M">

其余控制器方法:

@GetMapping(value = "/search/ad")
public ResponseEntity<List<SearchResultDTO>> findSearchResult(
@RequestParam(value="skey",required=true) String skey,
@RequestParam(value="fn",required=false,defaultValue = "null") String fn
) {
.....
}

异常是:"java.lang.NumberFormatException:对于输入字符串:"M&M">

我也尝试了以下方法:

fn="M%26M" , fn="M%26amp;M" , fn="M&M" 在下面的每种情况下都是我得到的例外。

"java.lang.NumberFormatException: 对于输入字符串: "M%26M", "M%26amp;M" "M&M">

正如建议的那样,我在下面尝试了.

@SpringBootTest(类 = 应用程序.class,Web环境 = SpringBootTest.WebEnvironment.RANDOM_PORT( 公共类 SearchIntegrationTest {

@LocalServerPort
private int port;
@Autowired
TestRestTemplate testRestTemplate;
@Test
public void findearchResult_IntegrationTest() throws JSONException {
String url = UriComponentsBuilder.fromUriString("/search/ad").queryParam("skey", "uc")
.queryParam("pf", "C&S").encode().toUriString();
ResponseEntity<String> response = testRestTemplate.getForEntity(url, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}

}

错误是:java.lang.NumberFormatException:对于输入字符串:"C%26S">

试试这个:

@GetMapping("/example")
public Map<String, String[]> getExample(HttpServletRequest request) {
return request.getParameterMap();
}

URI 将是:

?skey="uc"&fn="M%26M"

以及 JSON 格式的响应

{
"skey": [
""uc""
],
"fn": [
""M&M""
]
}

如果您知道单个参数的名称,也可以使用

request.getParameter("skey");

发送请求时必须进行 URL 编码。如果要手动测试 API,则必须自己对其进行编码。

例如。

http://loacalhost:8080/search/ad?skey="uc%26fn%3D%22M%26M"

否则,如果您使用 RestTemplate 来测试此 API,那么您可以使用如下所示的内容:

例如。

String url = UriComponentsBuilder
.fromUriString("http://loacalhost:8080/search/ad")
.queryParam("skey", "uc&fn="M&M").encode().toUriString();
new RestTemplate().getForEntity(url, String.class).getBody();

最新更新