开发中很常见的一个用例,操作完成后返回操作页面。
用代码表示就是:
response.sendRedirect(request.getHeader("referer"));
spring MVC里有RedirectView,如果能够把referer带上就更方便了。好在spring很灵活,自己增加这个功能吧。
实现一个View接口:
public class RefererRedirectView implements View{ protected static final Log logger = LogFactory.getLog(RefererRedirectView.class); /* (non-Javadoc) * @see org.springframework.web.servlet.View#getContentType() */ public String getContentType() { return null; } /* (non-Javadoc) * @see org.springframework.web.servlet.View#render(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { String returnUrl = request.getHeader("referer"); if(returnUrl==null || returnUrl.trim().equals("")){ returnUrl = "/"; } logger.debug("referer url["+returnUrl+"]"); response.sendRedirect(returnUrl); } }
ViewResolver 这个接口的实例可以在spring容器里有多个,组成一个链式结构,第一个如果无法处理转交下一个,直到被处理或全部失败。
再实现一个ViewResolver接口:
public class RefererViewResolver implements ViewResolver,Ordered { protected Log logger = LogFactory.getLog(getClass()); //以referer:起始的viewName,将被此ViewResolver处理 public static final String REFERER_PROFIX = "referer:"; /* (non-Javadoc) * @see org.springframework.web.servlet.ViewResolver#resolveViewName(java.lang.String, java.util.Locale) */ public View resolveViewName(String viewName, Locale locale) throws Exception { if (!viewName.startsWith(REFERER_PROFIX)) { return null; } logger.debug("this is referer view."); return new RefererRedirectView(); } /* (non-Javadoc) * @see org.springframework.core.Ordered#getOrder() */ public int getOrder() { return Integer.MAX_VALUE-1;//这个ViewResolver排在UrlBasedViewResolver前一个的位置 } }
最后,在配置文件中声明这个viewResolver:
<bean class="com.........RefererViewResolver"/>
这样,凡是以referer:起始的viewName,都会被redirect到请求发起的页面。
附测试类:
@Controller public class SomeController { @RequestMapping("/test_referer.do") public String referer(){ System.out.println("do some thing ,then return to referer."); return "referer:"; } @RequestMapping("/test_test1.do") public String test1(){ return "front/user/test1"; } @RequestMapping("/test_test2.do") public String test2(){ return "front/user/test2"; } }