重定向代码
@WebServlet("/responsedemo1")
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 访问这个资源自动跳转demo2
//1、设置状态码为302
resp.setStatus(302);
//2、设置响应头location
resp.setHeader("location","/day15_response_war_exploded/responsedemo2");
System.out.println("demo1被调用了");
//简单的重定向方法,只需要一句,上面的1,2可以删除
resp.sendRedirect("/day15_response_war_exploded/responsedemo2");
}
@WebServlet("/responsedemo2")
public class ResponseDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo2被访问了,");
}
面试题:forward和redirect的区别。
重定向的特点:redirect
1、地址栏发生变化
2、重定向可以访问其他站点(服务器)的资源
3、重定向是两次请求,不能使用request对象来共享数据
转发的特点:forward
1、转发地址栏路径不变
2、转发只能访问当前服务器下的资源
3、转发是一次请求,可以使用request对象来共享数据
路径的写法
1、相对路径:通过相对路径不可以确定唯一资源
* 如:. /index.html
*不以/开始,以.开头路径
*规则:确定访问当前资源和目标资源之间的相对位置关系
* ./当前目录
../后退一级目录
2、绝对路径:通过绝对路径可以确定唯一资源
*如:http://localhost//day15_response_war_exploded/responsedemo1
*以/开头的路径
*规则:判断定义的路径是给谁使用的?判断请求将来从哪儿发出
*给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
*建议虚拟目录动态获取,request.getContextpath()
*<a> <from> <重定向>
*给服务器使用:不需要加虚拟目录
*转发路径