转发和重定向

创建一个servlet类:

package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class Servlet2
 */斜体样式
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L; 
    public Servlet2() {
        super();
    }	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String header=request.getHeader("User-Agent");
		System.out.println("用户的浏览器信息:"+header);
		//1.重定向,告诉浏览器重新请求另一个资源
		/*用户发送Servlet2请求给服务器显示成功的页面,服务器告诉浏览器重新定位到新的资源,浏览器发送第二次请求,请求success.html页面,服务器响应*/
		//response.sendRedirect("success.html");
		//2.转发,服务器处理完成以后转交到另外一个资源。
		/*用户发送Servlet2请求给服务器显示成功的页面,服务器转发到success.html页面响应*/
		request.getRequestDispatcher("success.html").forward(request, response);
	}
}
//转发和重定的区别			转发			重定向
/*1.浏览器地址			不会发生变化,重定向发生变化
 *2.request				同一个请求		再次请求
 *3.API					request对象		request对象
 *4.位置					服务器内部完成	浏览器完成
 *5.WEN-INF				 可以访问		 不能访问
 *6.共享请求域数据		 可以共享		不能共享
 *7.目标资源		   当前web项目中的资源        不局限于当前web项目
 * */

首页:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>我是页面</h1>
<!-- http://localhost:8080/test/test.html -->
<a href="Servlet2">Servlet2</a>
</body>
</html>

响应页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>提交成功</h1>
</body>
</html>

你可能感兴趣的:(转发和重定向)