
-request.getRequestDispatcher(URL地址).forward(request,response)
Servlet调用forward()方法,服务器Servlet把目标资源返回给客户端浏览器request 作用域 request.setAttribute("name","Tom");
Servlet做出业务逻辑处理Servlet调用response.sendRedirect("xxx.jsp")方法,把要访问的目标资源作为response响应信息发送给客户端浏览器WEB- INF下的文件,浏览器上的窗口地址会改版,可以用于跳转第三方地址或者应用里面的其他Servlet、Jsp等sendRedirect()方法,会在响应中设置Location响应报头,这个过程对于用户来说是透明的,浏览器会自动完成新的访问http开头,则认为是当前应用里面的Servlet重定向,默认加上应用上下文;如果加上http则会使用配置的全路径进行跳转
@WebServlet("/forward")
public class DispatchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("net.fl.web.DispatchServlet doGet");
// req.setAttribute("name","fl");
User user = new User();
user.setHost("http://fl");
user.setId(1);
user.setName("fl");
req.setAttribute("user",user);
//请求转发
// req.getRequestDispatcher("index.jsp").forward(req, resp);
// req.getRequestDispatcher("request").forward(req, resp);
//重定向
//内部跳转
resp.sendRedirect("/index.jsp");
//外部站点跳转
// resp.sendRedirect("https://baidu.com");
}
}public class User {
private int id;
private String name;
private String host;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}<%@ page contentType="text/html; charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
<div>JSP页面</div>
index.jsp
<hr>
name:${user.name}
<hr>
id:$user.id}
<hr>
host:${user.host}
</body>
</html>
