在前面的例子中,无论是/index跳转到index.jsp 还是/addProduct 跳转到showProduct.jsp,都是服务端跳转。
本例讲解如何进行客户端跳转
步骤 1 : 修改IndexController
首先映射/jump到jump()方法
在jump()中编写如下代码
ModelAndView mav = new ModelAndView(“redirect:/index”);
redirect:/index
即表示客户端跳转的意思
package 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 Spring MVC”);
return mav;
}
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav = new ModelAndView("redirect:/index");
return mav;
}
}
步骤 2 : 测试
访问页面
http://127.0.0.1:8080/springmvc/jump
结果客户端跳转到了
127.0.0.1:8080/springmvc/index