源代码:
https://download.csdn.net/download/qzc70919700/19886805
一、发送请求
1.1、请求转发
关键字:forward
相对路径转发:return ”forward:list.do“;
代码:
/**
* 请求转发,相对路径
* http://localhost:8080/mvc_demo04/test/t1.do
* @return
*/
@RequestMapping("/t1.do")
public String test1(HttpServletRequest request) {
System.out.println("——相对路径请求转发测试——");
request.setAttribute("str", "hello");
return "forward:restlt.do";
}
绝对路径转发:return ”forward:/user/list.do“;
代码:
/**
* 请求转发,绝对路径
* http://localhost:8080/mvc_demo04/test/t1_1.do
* @return
*/
@RequestMapping("/t1_1.do")
public String test1_1(HttpServletRequest request) {
System.out.println("——绝对路径请求转发测试——");
request.setAttribute("str", "hello");
return "forward:/test/restlt.do";
}
Ps:user根路径前面必须有/
1.2、重定向
关键字:redirect
相对路径重定向:return ”redirect:list.do“;
代码:
/**
* 重定向,相对路径
* http://localhost:8080/mvc_demo04/test/t2.do
* @return
*/
@RequestMapping("/t2.do")
public String test2(HttpServletRequest request) {
System.out.println("——相对路径重定向测试——");
request.setAttribute("str", "hello");
return "redirect:restlt.do";
}
绝对路径重定向:return ”redirect:list.do“;
代码:
/**
* 重定向,绝对路径
* http://localhost:8080/mvc_demo04/test/t2_1.do
* @return
*/
@RequestMapping("/t2_1.do")
public String test2_1(HttpServletRequest request) {
System.out.println("——绝对路径重定向测试——");
request.setAttribute("str", "hello");
return "redirect:/test/restlt.do";
}
二、接收转发/重定向的结果,测试读取request中的内容
2.1、接收转发/重定向的结果的代码
/**
* 接收转发/重定向结果
* @param str
* @return
*/
@RequestMapping("/restlt.do")
public String restlt(HttpServletRequest request) {
System.out.println("restlt --> "+request.getAttribute("str"));
return "index";
}
运行结果: