public class TestServletScope extends HttpServlet { //作用域经典案例测试 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. request 表示当前请求的范围 if(request.getAttribute("count")==null) { request.setAttribute("count", 1); }else { request.setAttribute("count", (Integer)(request.getAttribute("count"))+1); } //2. session 表示当前会话的范围 HttpSession session = request.getSession(); if(session.getAttribute("count")==null) { session.setAttribute("count", 1); }else { session.setAttribute("count", (Integer)(session.getAttribute("count"))+1); } //3. application 表示当前应用的范围 ServletContext application = request.getServletContext(); if(application.getAttribute("count")==null) { application.setAttribute("count", 1); }else { application.setAttribute("count", (Integer)(application.getAttribute("count"))+1); } //请求重定向 request.getRequestDispatcher("result").forward(request, response); } }
public class ResultServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request int count1 = (Integer)request.getAttribute("count"); response.getWriter().println("request:"+count1); //session HttpSession session = request.getSession(); int count2 = (Integer)session.getAttribute("count"); response.getWriter().println("session:"+count2); //application ServletContext app = request.getServletContext(); int count3 = (Integer)app.getAttribute("count"); response.getWriter().println("application:"+count3); } }
运行结果:request值一直不变。当重新请求 session值加一,,关闭浏览器后 session值变为1 . 只有关闭tomcat ,application 才变成1,不然重新请求一直递增。
浏览器的请求发送给组件1,组件1经过一些处理之后,将request和response对象“传递”给组件2,由组件2继续处理,然后输出响应(当然,也可以继续向其他组件“传递”),这个传递的过程称之为“转发”。
整个过程只涉及一次浏览器和服务器之间的“请求-响应”,转发过程中的组件共享同一个请求(request)和响应(response)对象。
特点:
1. 转发过程中浏览器地址栏路径没变,共享同一个请求对象,在请求中共享数据,响应由最后一个决定。
2. 只能够访问当前应用中的资源,包括WEB-INF中的资源,不能够跨域跳转(老师我想跳转到源代码官网去看视频...)
3.一般用于用户登陆的时候,根据角色转发到相应的模块.
4. 疑问: 既然可以访问WEB-INF中的资源了,那怎么之前又说放在里安全呢?
a) 程序没有提供的路径就不能够访问;
b) 在跳转之前可以做权限判断
是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址.所以地址栏显示的是新的URL.
特点:
1. 浏览器中地址会变,发送了两个请求,相当于访问了两次。
2. 因为是不同的请求,所以不能够共享请求中的数据,最终的响应是由最后一个Servlet决定。
3. 可以跨域访问资源(尝试访问itsource.cn),不能够访问WEB-INF中的资源
4.一般用于用户注销时返回主页面或跳转到其它的网站等
原文:https://www.cnblogs.com/gshao/p/10311807.html