【问题标题】:Java Spring MVC Redirect with Regular expression带有正则表达式的 Java Spring MVC 重定向
【发布时间】:2013-10-30 14:34:52
【问题描述】:

所以我有这个重定向视图我的控制器之一:

    @RequestMapping(value = {"/shoes", "/shoes/"}, method = {RequestMethod.GET})
    public RedirectView shoesHome(HttpServletRequest request) {
        return new RedirectView("https://www.somewebsite.com/");
    }

是否可以添加正则表达式以便重定向发生

which currently is working fine and any other variation such as 
http://mywebsites.com/shoes 
http://mywebsites.com/shoes/sandals.html
http://mywebsites.com/shoes/boots.html
http://mywebsites.com/shoes/sport/nike.html

谢谢

【问题讨论】:

  • 我不明白你在期待什么。
  • 所以现在如果我去 mywebsite.com/shoes 它会重定向到 somewbsite.com 但是如果我输入 somewebsite.com/shoes/sandals.html 它不会,它仍然会去 .鞋/凉鞋.html。是否可以使用正则表达式,以便包含 shoes/ 的每个请求仍将重定向到 somewebsite.com ?

标签: java regex spring spring-mvc redirect


【解决方案1】:

你可以这样做:-

@RequestMapping(value = "/shoes/**", method = RequestMethod.GET)
public RedirectView shoesHome() {
    return new RedirectView("https://www.somewebsite.com/");
}

这样,/shoes 之后的任何 URI 也将被重定向到 http://somewebsite.com

这里是测试用例:-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:springtest-test.xml"})
public class MyControllerTest {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Test
    public void testRedirect() throws Exception {
        assertRedirect("/shoes");
    }

    @Test
    public void testRedirect2() throws Exception {
        assertRedirect("/shoes/sandals.html");
    }

    @Test
    public void testRedirect3() throws Exception {
        assertRedirect("/shoes/sports/nike.html");
    }

    private void assertRedirect(String uri) throws Exception {
        MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
        MockHttpServletResponse response = new MockHttpServletResponse();

        Object handler = handlerMapping.getHandler(request).getHandler();
        ModelAndView modelAndView = handlerAdapter.handle(request, response, handler);

        RedirectView view = (RedirectView) modelAndView.getView();
        assertEquals("matching URL", "https://www.somewebsite.com/", view.getUrl());
    }
}

【讨论】:

    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 2018-03-14
    • 2013-07-25
    • 2019-07-02
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多