spring-mvc - 与 spring @RequestParam 不一致的自动解码

标签 spring-mvc spring-boot spring-test

我有一个普通的 spring @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
origin自动解码,等于 http://www.example.com/index.html?a=b#/route
但是当我写了一个 spring mvc 测试时:
@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
    }
}

当我调试这个测试和 Controller 时,origin这次没有解码。只是想知道为什么它在这两种情况下表现不同。

最佳答案

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

所以,只需使用 original测试中的原始值,它应该可以正常工作。

换句话说,使用这个:

@RunWith(SpringRunner.class)
@WebMvcTest(WeChatOauthController.class)
public class WeChatOauthControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void itShouldRedirectToWeChatToFinishOauthProtocol() throws Exception {
        this.mvc.perform(get("/wechat/browser")
            .param("origin", "http://www.example.com/index.html?a=b#/route"))
            .andDo(print())
        //omitted codes
    }
}

关于spring-mvc - 与 spring @RequestParam 不一致的自动解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383940/

相关文章:

java - Spring过滤器抛出自定义异常

java - 错误 : No URL for ServletContext resource when running Spring integrated test

java - Spring Junit 不工作

java - 如何使用 Spring Boot 防止危险 Controller 包含在生产配置文件中?

angular - 使用后端验证流程澄清的 Google 登录

java - Spring Boot 2.0.2 MultipartConfigElement 未配置为 MultipartFile

java - 不是托管类型。 Spring 启动测试

java - Spring框架和tomcat - 如何启用以下文件夹符号链接(symbolic link)?

java - 数据未持久保存到数据库并在控制台中显示空指针异常

java - 在 Java 中实现 WebSocket