ServletContext:全局对象(域对象)、请求转发和重定向的区别

ServletConfig对象

ServletConfig:称为Servlet配置对象,每一个Servlet可以有自己的配置,可以加载web.xml文件的时候,就可以在servlet的基本配置配置一些初始化参数,就可以在Servlet中获取初始化参数的内

举例:获取指定的文件的路径—完成IO流操作
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Enumeration;

public class ServletConfigDemo extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //public String getInitParameter(String name):servletConfig里面的方法:通过初始化参数名称获取参数值
        //1)获取到配置对象:在他父类的父类的GenericServlet:ServletConfig getServletConfig()
        ServletConfig servletConfig = this.getServletConfig();
        //2)public String getInitParameter(String name)
        String path = servletConfig.getInitParameter("path");
        System.out.println(path);
        //3)io流操作       a.txt文件中打印”hello“
        FileWriter fw = new FileWriter(path+"a.txt") ;
        fw.write("hello");
        fw.flush();

        //3)关闭资源
        fw.close();
        System.out.println("----------------------------------------") ;
        //public java.util.Enumeration<E> getInitParameterNames():获取servlet的所有初始化参数名称
        Enumeration<String> en = servletConfig.getInitParameterNames();
        //里面有特有功能:boolean hasMoreElements()  判断是有更多的元素
        //Object nextElement():获取下一个元素
        while(en.hasMoreElements()){
            String initParamenterName = en.nextElement();
            //public String getInitParameter(String name):通过参数名称获取参数值
            String initParameterValue = servletConfig.getInitParameter(initParamenterName);
            System.out.println(initParamenterName+"---"+initParameterValue);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    }
}

ServletContext:全局对象(域对象):整个web应用程序的范围

ServletContext:重点对象(全局对象)————代表整个web应用程序,每一个web应用程序都有自己的上下文

作用一:获取web应用程序的上下文路径
前端  浏览器行为;----都需要带上上下文路径
	<a href="http://localhost:8080/web上下文路径/xx地址"></a>
	<img src="都需要带上下文路径" />
导入js文件
	<script src="都需要带上下文路径"></script>
导入css文件
	<link href="都需要带上下文路径" ref="stylesheet">
public class ContextServletDemo1 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext接口对象----->web容器 帮助我们创建对象了
        
        //public ServletContext getServletContext()
        //ServletContext servletContext = this.getServletContext();
        
        //获取上下文路径---->public String getContextPath()
        
        //String contextPath = servletContext.getContextPath();
        //System.out.println(contextPath);
        
        //简化书写格式:全局对象中的功能一部分都封装在请求对象中
        //String getContextPath()
        
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
作用二:获取web.xml文件中全局参数
public class ContextServletDemo2 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1)获取全局对象
        
        ServletContext servletContext = this.getServletContext();
        
        //2)获取全局参数
        //public String getInitParameter(String name):获取全局参数
        
        String encoding = servletContext.getInitParameter("encoding");
        
        //3)获取参数encoding的值---解决post提交中文乱码  (后期:使用过滤器)
        
        request.setCharacterEncoding(encoding);

        //获取用户的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---"+password) ;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doGet(request,response);
    }
}

作用三:请求转发使用

请求转发---->服务器帮助我们转发到资源文件上------"服务器行为"是不需要带上下文路径

public class ContextServletDemo3 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //请求转发本身的写法格式:
        //1)获取全局对象Servletcontext
        
        //ServletContext servletContext = this.getServletContext();

        //2)创建一个转发器对象
        
        //public RequestDispatcher getRequestDispatcher(String path)
        //RequestDispatcher:定义接收来自客户端的请求并将它们发送到服务器上的任何资源
        //RequestDispatcher rd = servletContext.getRequestDispatcher("/adv.html");//参数:转发的资源路径:路径上不能带上下文的,直接写资源路径(以"/开头")

        //3)使用RequestDispatcher转发去对象 去请求转发到静态资源或者动态资源上
        
        //public void forward(ServletRequest request, ServletResponse response)
        //rd.forward(request,response);

        //简写格式:直接就可以请求对象HttpServletRequest获取RequestDispatcher
        //public RequestDispatcher getRequestDispatcher(String path)

        //request.getRequestDispatcher("/adv.html").forward(request,response);

        //请求转发可以访问WEB-INF下的资源文件

        request.getRequestDispatcher("/WEB-INF/hello.html").forward(request,response);

        System.out.println("请求转发完成");

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
    }
}
作用四:作为域对象

四个域对象:从小到大

  • pageContext page对象 在某个jsp页面中有效

  • HttpServletRequest request对象 在一次请求中有效 (举例:请求转发) :使用居多

  • HttpSession session对象 (会话管理)里面一种技术 :其次,使用居多

  • ServletContext context对象 全局对象 :代表整个web应用程序

public class ContextServletDemo4 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1)获取全局对象
        ServletContext servletContext = this.getServletContext();
        //2)public void setAttribute(String name, Object object):给全局对象(域对象)绑定属性以及它的内容
        //创建一个集合
        List<String> list = new ArrayList<>() ;
        //添加内容
        list.add("张三") ;
        list.add("高圆圆") ;
        list.add("文章") ;
        servletContext.setAttribute("list",list);
        System.out.println("-------------------");
        servletContext.setAttribute("name","刘桑");

        System.out.println("存储数据成功....");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

Request、Response(掌握请求对象中一些常用的功能以及响应对象的重定向原理)

浏览器将所有的信息都封装到HttpServletRequest对象中,获取请求的信息

public class RequestDemo1 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1)获取请求行的内容 请求方式 URI HTTP协议版本
        //String getMethod()
        String method = request.getMethod();
        System.out.println("请求方式是:"+method);
        //StringBuffer getRequestURL();
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("请求的url地址是:"+requestURL.toString());
        //String getRequestURI();
        System.out.println("请求的uri是:"+request.getRequestURI()) ;

        // String getProtocol();获取协议版本
        System.out.println("http版本是:"+request.getProtocol());

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

浏览器携带的请求头有一个:User-Agent头表示的意思是:用户使用的浏览器的类型

public class RequestDemo2 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //请求对象中获取请求头的方法:
        //public String getHeader(String name):通过指定的请求头获取它的内容
        String header = request.getHeader("user-agent");
        //判断用户使用的浏览器的类型时
        if(header.contains("Chrome")){
            System.out.println("用户使用的谷歌浏览器") ;
        }else if(header.contains(" Firefox")){
            System.out.println("用户使用的是火狐浏览器") ;
        }else if(header.contains("trident")){
            System.out.println("用户的是IE浏览器");
        }else{
            System.out.println("未知浏览器类类型");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doGet(request,response);
    }
}

浏览器请求服务器的时候,服务器将所有响应信息封装到HttpServletResponse

Http协议的一种规范要求:固定的格式

​ 服务器:tomcat,Jetty,nginx

服务器响应给浏览器 :响应信息

​ 响应行:两部分————Http协议版本、响应的状态码

​ 响应头:key:value

响应的状态码:

​ 404:未找到的路径(前端错误)

​ 405:请求方式有问题

​ 500:后端代码错误(业务逻辑出问题了…)

​ 200:响应成功

​ 302:进一步发送请求

​ 跨域(Springboot +vue)问题(三阶段末尾)

重定向的原理:(重定向最终属于浏览器行为: 必须携带上下文路径)

​ 当用户发送一次请求—>服务器接收请求,响应给浏览器

​ location响应头

​ 响应的状态码:302 进一步请求

public class ResponseDemo extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1)发送请求:http://localhost:8080/Servlet_jsp/responseDemo

        //2)重定向原理:通过响应对象设置响应头:loaction
        //public void setHeader(String name, String value)
      	//response.setHeader("location",request.getContextPath()+"/adv.html") ;
        //设置一个响应状态码 302
        //public void setStatus(int sc)
      	//response.setStatus(302) ;

        //给浏览器响应
      	//System.out.println("response successful...");

        //简写格式:响应对象有一个方法:
        //public void sendRedirect(String location) throws java.io.IOException
		//response.sendRedirect(request.getContextPath()+"/adv.html");

        //重定向访问WEB-INF下的文件
        response.sendRedirect(request.getContextPath()+"/WEB-INF//adv.html");

        //重定向到另一个工程资源文件
		//response.sendRedirect("http://localhost:8081/Servlet_01/login.html");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

面试题:请求转发和重定向的区别(重点)

1)地址栏是否有明显变化
	请求转发没有变化的:
	重定向地址栏有明显变化
2)它们整个的两次request对象是否一致
    请求转发:服务器内部完成的---->(服务器行为:不需要携带上下文路径),两次request对象是一致的!
    重定向————原理:
    	设置一响应头:location+302状态码 
    	第一次请求的后台地址,然后给响应浏览器 302状态以及location地址,浏览器会再一次发送请求
    	两次request对象不一致,所以如果有业务需求的话,使用重定向获取不到request域对象中的数据的;
    	如果仅仅页面跳转,使用重定向!
 3)是否能够访问WEB-INF下的资源文件
 		WEB-INF:可以存放html/jsp文件,都是为了保证数据安全;是不能够直接访问的
 		WEB-INF:只能请求转发的方式来访问,重定向不可以访问的
 4)是否能够跨工程访问其他工程里面的资源文件
 		请求转发:只能访问当前工程下的文件包括WEB-INF的资源文件
 		重定向:可以访问 当前工程下的资源文件(除过WEB-INF),还可以跨工程访问其他资源文件...

MVC架构思想,描述

三层架构思想:
	M:Model:业务模型数据
		包名 xxx.xx.service————业务层代码(业务逻辑判断)
		包名 xx.xx.xx.dao—————数据库访问层代码(JDBC方式访问数据库的操作)
	V:View:视图数据
		现在使用jsp/   (html+Jquery+ajax)—————服务器端返回给前端都是"json数据"
	C:Controller:控制器(前端和后端的连接器)  :控制视图
		前后端交互:
			现在技术就是Servlet:调用service层接口--->获取业务数据---->交给前端
			使用jsp技术:将业务数据获取到之后存"储域对象",然后请求转发给xxx.jsp
				    
以后的技术Springmvc:spring提供的框架

Servlet的xml配置方式流程

当前这个类继承HttpServlet
重写doGet()/doPost()方法
完成xml配置

servlet的基本配置
	<servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.qf.controller.LoginServlet</servlet-class>
    </servlet>
servlet的映射配置
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

Jsp运行经历哪个阶段

hello.jsp---->被翻译成 hello_jsp.java文件
class hello_jsp entends HttpJspBase----->导入jasper.jar---->HttpJspBase 继承了HttpServlet
被tomcat解析---->创建当前类对象---->反射的创建对象---->调用_jspservice()--->解析jsp文件中html标签代码
   ------hello_jsp.java----->hello_jsp.class文件  (编译)
      
    默认jsp的存储路径C:\Users\Administrator\.IntelliJIdea2019.1\system\tomcat\Unnamed_servlet+jsp+jdbc\work\Catalina\localhost\servlet_jsp_jdbc\org\apache\jsp
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值