简体   繁体   中英

Spring MVC Relative Redirect from HttpServletResponse

Given this methodology of relative redirect to another controller:

@Controller
@RequestMapping("/someController")
public class MyController {
    @RequestMapping("/redirme")
    public String processForm(ModelMap model) {            
        return "redirect:/someController/somePage";
    }
}

How can I simulate that same relative redirect given that I'm within an interceptor?

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        response.sendRedirect("/someController/somePage");
        return false;
    }
}

Now with the interceptor, i will end up at application.com/someController/somePage when I really want to be at application.com/deployment/someController/somePage. Surely there must be a 'spring' solution for this?

Converting my comment to an answer -

Try using response.sendRedirect(request.getContextPath() + uri);

After referencing the redirect documentation ,reviewing the source code for UrlBasedViewResolver, and gotuskar's comment, I feel silly for not knowing this would work and have a solution:

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        StringBuilder targetUrl = new StringBuilder();
        if (this.redirectURL.startsWith("/")) {
            // Do not apply context path to relative URLs.
            targetUrl.append(request.getContextPath());
        }
        targetUrl.append(this.redirectURL);

        if(logger.isDebugEnabled()) {
            logger.debug("Redirecting to: " + targetUrl.toString());
        }

        response.sendRedirect(targetUrl.toString());
        return false;
    }
}

正如在春季回答更近期的问题上下文路径与url-pattern重定向一样 ,你可以使用ServletUriComponentsBuilder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM