Spring mvc結果跳轉方法詳解
ModelAndView
設置ModelAndView對象 , 根據view的名稱 , 和視圖解析器跳到指定的頁面 .
頁面 : {視圖解析器前綴} + viewName +{視圖解析器后綴}
<!-- 視圖解析器 --><bean id='internalResourceViewResolver'> <!-- 前綴 --> <property name='prefix' value='/WEB-INF/jsp/' /> <!-- 后綴 --> <property name='suffix' value='.jsp' /></bean>
對應的controller類
public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一個模型視圖對象 ModelAndView mv = new ModelAndView(); mv.addObject('msg','ControllerTest1'); mv.setViewName('test'); return mv; }}
ServletAPI
通過設置ServletAPI , 不需要視圖解析器 .
通過HttpServletResponse進行輸出 通過HttpServletResponse實現重定向 通過HttpServletResponse實現轉發@Controllerpublic class ResultGo { @RequestMapping('/result/t1') public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.getWriter().println('Hello,Spring BY servlet API'); } @RequestMapping('/result/t2') public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.sendRedirect('/index.jsp'); } @RequestMapping('/result/t3') public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception { //轉發 req.setAttribute('msg','/result/t3'); req.getRequestDispatcher('/WEB-INF/jsp/test.jsp').forward(req,rsp); }}
SpringMVC
通過SpringMVC來實現轉發和重定向 - 無需視圖解析器;
測試前,需要將視圖解析器注釋掉
@Controllerpublic class ResultSpringMVC { @RequestMapping('/rsm/t1') public String test1(){ //轉發 return '/index.jsp'; } @RequestMapping('/rsm/t2') public String test2(){ //轉發二 return 'forward:/index.jsp'; } @RequestMapping('/rsm/t3') public String test3(){ //重定向 return 'redirect:/index.jsp'; }}
通過SpringMVC來實現轉發和重定向 - 有視圖解析器;
重定向 , 不需要視圖解析器 , 本質就是重新請求一個新地方嘛 , 所以注意路徑問題.
可以重定向到另外一個請求實現
@Controllerpublic class ResultSpringMVC2 { @RequestMapping('/rsm2/t1') public String test1(){ //轉發 return 'test'; } @RequestMapping('/rsm2/t2') public String test2(){ //重定向 return 'redirect:/index.jsp'; //return 'redirect:hello.do'; //hello.do為另一個請求/ }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)2. ASP.NET MVC通過勾選checkbox更改select的內容3. Android實現圖片自動切換功能(實例代碼詳解)4. jsp+mysql實現網頁的分頁查詢5. Python使用oslo.vmware管理ESXI虛擬機的示例參考6. 存儲于xml中需要的HTML轉義代碼7. javascript xml xsl取值及數據修改第1/2頁8. 解決Python paramiko 模塊遠程執行ssh 命令 nohup 不生效的問題9. JavaScript Tab菜單實現過程解析10. 使用AJAX(包含正則表達式)驗證用戶登錄的步驟
