Spring mvc結(jié)果跳轉(zhuǎn)方法詳解
ModelAndView
設(shè)置ModelAndView對(duì)象 , 根據(jù)view的名稱 , 和視圖解析器跳到指定的頁面 .
頁面 : {視圖解析器前綴} + viewName +{視圖解析器后綴}
<!-- 視圖解析器 --><bean id='internalResourceViewResolver'> <!-- 前綴 --> <property name='prefix' value='/WEB-INF/jsp/' /> <!-- 后綴 --> <property name='suffix' value='.jsp' /></bean>
對(duì)應(yīng)的controller類
public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一個(gè)模型視圖對(duì)象 ModelAndView mv = new ModelAndView(); mv.addObject('msg','ControllerTest1'); mv.setViewName('test'); return mv; }}
ServletAPI
通過設(shè)置ServletAPI , 不需要視圖解析器 .
通過HttpServletResponse進(jìn)行輸出 通過HttpServletResponse實(shí)現(xiàn)重定向 通過HttpServletResponse實(shí)現(xiàn)轉(zhuǎn)發(fā)@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 { //轉(zhuǎn)發(fā) req.setAttribute('msg','/result/t3'); req.getRequestDispatcher('/WEB-INF/jsp/test.jsp').forward(req,rsp); }}
SpringMVC
通過SpringMVC來實(shí)現(xiàn)轉(zhuǎn)發(fā)和重定向 - 無需視圖解析器;
測試前,需要將視圖解析器注釋掉
@Controllerpublic class ResultSpringMVC { @RequestMapping('/rsm/t1') public String test1(){ //轉(zhuǎn)發(fā) return '/index.jsp'; } @RequestMapping('/rsm/t2') public String test2(){ //轉(zhuǎn)發(fā)二 return 'forward:/index.jsp'; } @RequestMapping('/rsm/t3') public String test3(){ //重定向 return 'redirect:/index.jsp'; }}
通過SpringMVC來實(shí)現(xiàn)轉(zhuǎn)發(fā)和重定向 - 有視圖解析器;
重定向 , 不需要視圖解析器 , 本質(zhì)就是重新請(qǐng)求一個(gè)新地方嘛 , 所以注意路徑問題.
可以重定向到另外一個(gè)請(qǐng)求實(shí)現(xiàn)
@Controllerpublic class ResultSpringMVC2 { @RequestMapping('/rsm2/t1') public String test1(){ //轉(zhuǎn)發(fā) return 'test'; } @RequestMapping('/rsm2/t2') public String test2(){ //重定向 return 'redirect:/index.jsp'; //return 'redirect:hello.do'; //hello.do為另一個(gè)請(qǐng)求/ }}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解瀏覽器的緩存機(jī)制2. HTML5 Canvas繪制圖形從入門到精通3. jsp EL表達(dá)式詳解4. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器5. 爬取今日頭條Ajax請(qǐng)求6. css代碼優(yōu)化的12個(gè)技巧7. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))8. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法9. asp批量添加修改刪除操作示例代碼10. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)
