0

So I have this redirect view one of my controllers:

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

Is it possible to add a regular expression so that the redirect will happen for

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

Thank you

2
  • I don't understand what you are expecting. Commented Oct 21, 2013 at 22:17
  • So right now if I go to mywebsite.com/shoes it will redirect to somewbsite.com but if I type somewebsite.com/shoes/sandals.html it will not, it will still go to .shoes/sandals.html. Is it possible to use a regular expression so every request that contains shoes/ will still redirect to somewebsite.com ? Commented Oct 21, 2013 at 22:20

1 Answer 1

2

You can do this:-

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

With this, any URI after /shoes will also get redirected to http://somewebsite.com.

Here are the testcases:-

@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());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.