使用spring @RequestParam进行不一致的自动解码

问题描述 投票:2回答:2

我有一个普通的弹簧@Controller,它采用URL编码的字符串作为参数:

@RequestMapping(value = "/wechat/browser", method = GET)
public void askWeChatWhoTheUserIs(@RequestParam(name = "origin") String origin,
                                  HttpServletResponse response) throws IOException {
    //omitted codes
}

当我调试spring boot应用程序并使用浏览器测试端点时:

curl http://localhost:8080/wechat/browser\?origin\=http%3A%2F%2Fwww.example.com%2Findex.html%3Fa%3Db%23%2Froute

qazxsw poi自动解码并等于qazxsw poi

但是当我写一个spring mvc测试时:

origin

当我调试这个测试和控制器时,http://www.example.com/index.html?a=b#/route这次没有被解码。只是想知道为什么它在这两种情况下表现不同。

spring-mvc spring-boot spring-test
2个回答
1
投票

在使用Spring MVC Test框架提供请求参数时,不需要手动编码参数的值,因为没有物理HTTP请求。

所以,只需在测试中使用@RunWith(SpringRunner.class) @WebMvcTest(WeChatOauthController.class) public class WeChatOauthControllerTest { @Autowired private MockMvc mvc; @Test public void itShouldRedirectToWeChatToFinishOauthProtocol() throws Exception { String origin = "http://www.example.com/index.html?a=b#/route"; String encodedOrigin = URLEncoder.encode(origin, "UTF-8"); this.mvc.perform(get("/wechat/browser") .param("origin", encodedOrigin)) .andDo(print()) //omitted codes } } 原始值,它应该可以正常工作。

换句话说,使用这个:

origin

0
投票

您可以使用此方法,因此将有适当的解码

original
© www.soinside.com 2019 - 2024. All rights reserved.