[TOC]
# 客戶端跳轉
在前面的例子中,無論是/index跳轉到index.jsp 還是/addProduct 跳轉到showProduct.jsp,都是服務端跳轉。
本例講解如何進行客戶端跳轉
## 步驟 1 : 先運行,看到效果,再學習
先將完整的項目(向老師要相關資料),配置運行起來,確認可用之后,再學習做了哪些步驟以達到這樣的效果。
## 步驟 2 : 模仿和排錯
在確保可運行項目能夠正確無誤地運行之后,再嚴格照著教程的步驟,對代碼模仿一遍。
模仿過程難免代碼有出入,導致無法得到期望的運行結果,此時此刻通過比較**正確答案** ( 可運行項目 ) 和自己的代碼,來定位問題所在。
采用這種方式,**學習有效果,排錯有效率**,可以較為明顯地提升學習速度,跨過學習路上的各個檻。
## 步驟 3 : 效果
訪問頁面
`http://localhost:8080/springmvc/jump`
結果客戶端跳轉到了
`http://localhost:8080/springmvc/index`

## 步驟 4 : 修改IndexController
首先映射/jump到jump()方法
在jump()中編寫如下代碼
~~~
ModelAndView mav = new ModelAndView("redirect:index");
~~~
redirect:/index
即表示客戶端跳轉的意思
~~~
package com.dodoke.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class IndexController {
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello SpringMVC");
return mav;
}
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav = new ModelAndView("redirect:index");
return mav;
}
}
~~~
## 步驟 5 : 測試
訪問頁面
`http://localhost:8080/springmvc/jump`
結果客戶端跳轉到了
`http://localhost:8080/springmvc/index`
