Day16_config;context;Request和Response;请求转发和重定向的区别(笔记)

Day16_config;context;Request和Response;请求转发和重定向的区别(笔记)

1.ServletConfig对象(了解):servlet配置对象

1.1作用

ServletConfig:称为Servlet配置对象,每一个Servlet可以有自己的配置
	可以加载web.xml文件的时候,就可以在servlet的基本配置配置一些初始化参数
    就可以在Servlet中获取初始化参数的内容(一个或者所有)
    	获取单个:public String getInitParameter(String name):servletConfig里面的方法:通过初始化参数名称获取参数值
    	获取所有:public java.util.Enumeration<E> getInitParameterNames():获取servlet的所有初始化参数名称  

1.2举例(代码步骤):

​ 获取指定的文件的路径—完成IO流操作

1.2.1 创建一个WEB工程,导tomcat包

1.2.2 create new servlet创建一个Servlet类

/**
 * ServletConfig:称为Servlet配置对象,每一个Servlet可以有自己的配置
 *      可以加载web.xml文件的时候,就可以在servlet的基本配置配置一些初始化参数
 *      就可以在Servlet中获取初始化参数的内容
 *
 *      举例:
 *              获取指定的文件的路径---完成IO流操作
 */
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流操作
        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);
    }
}

1.2.3 编写配置文件

可以在servlet的基本配置配置一些初始化参数

	<servlet>
        <servlet-name>ServletConfigDemo</servlet-name>
        <servlet-class>com.qf.servletconfig_01.ServletConfigDemo</servlet-class>
        <!--配置初始化参数-->
        <!--
            后期在学习框架 :加载配置文件
        -->
        <init-param>
            <!--初始化名称-->
            <param-name>path</param-name>
            <!--初始化的内容-->
            <param-value>D:\\Java\\IdeaProjects\\JavaEESecond15_\\Day16_Servlet+jsp\\</param-value>   <!-- 转义字符\\ -->
        </init-param>
        
        
        <!--配置初始化参数-->
        <init-param>
            <!--初始化名称-->
            <param-name>AAA</param-name>
            <!--初始化的内容-->
            <param-value>AAA'value</param-value>
        </init-param>

    </servlet>
    <servlet-mapping>
        <servlet-name>ServletConfigDemo</servlet-name>
        <url-pattern>/config</url-pattern>
    </servlet-mapping>

1.2.4 运行结果:

运行服务器 将浏览器的末尾加/config 回车

在项目下创建了一个a.txt文件 内容是hello

同时在控制台输出

D:\\Java\\IdeaProjects\\JavaEESecond15_\\Day16_Servlet+jsp\\


path—D:\\Java\\IdeaProjects\\JavaEESecond15_\\Day16_Servlet+jsp\\

AAA—AAA’value

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

作用:
		1)获取上下文路径   /web应用程序名称/访问地址
						/web应用程序名称
		2)获取全局参数---->举例子使用 web.xml---><context-param>---以后的目的:加载配置文件
		
		3)可以请求转发:后端 通过JDBC方式拿到数据了---->直接页面跳转将数据展示
		
		4)就是作为域对象---在不同servlet之间进行数据共享!

2.1 获取上下文路径

2.1.1 目的:

前端  浏览器行为;----都需要带上上下文路径
          <a href="http://localhost:8080/web上下文路径/xx地址"></a>
          <img src="都需要带上下文路径" />

         导入js文件
              <script src="都需要带上下文路径"></script>
         导入css文件
             <link href="都需要带上下文路径" ref="stylesheet">

2.1.2 代码:

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);
    }
}

输出结果:

/Day16_Servlet_jsp

(两种方式获得的内容一致)

2.2 获取全局参数

和上边1.1不一样 1.1是config 此时是context

2.2.1 配置文件代码 (这个的位置写在全局参数 写在<servlet 这个标签之外 <web-app标签之内)

<!--配置全局参数
        后期框架中:全局参数意义可以加载框架的配置文件

    -->
    <context-param>
        <!--全局参数名称-->
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </context-param>

2.2.2代码

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);//这个encoding字符串就是"utf-8"
        //以前用的方式 request.setCharacterEncoding("utf-8");这样是写死的,不好

        //获取用户的内容  这样通过post获取的数据在java控制台上不会乱码了
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---"+password) ;//张三---123
        
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            doGet(request,response);
    }
}

解释:

使用post获取到的中文在java控制台上显示会乱码

以前我们通过 request.setCharacterEncoding(“utf-8”);这个方式来处理

现在可以通过获取全局参数的方式获取字符串 request.setCharacterEncoding(servletContext.getInitParameter(“xxx”));

这样不用将UTF-8写死,比较灵活

2.3 可以请求转发

/**
 * ServletContext的作用3
 *      请求转发使用
 *
 *      请求转发---->服务器帮助我们转发到资源文件上------"服务器行为"是不需要带上下文路径
 *
 */

请求转发的方式注意事项,不用写上下文,而且可以访问到WEB-INF下边的.html资源,这是浏览器获取不到的,只能通过请求转发的方式来获取

代码:

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);
    }

}

2.4 就是作为域对象—在不同servlet之间进行数据共享!

ServletContext作用4:作为域对象

 四个域对象:从小到大
        pageContext          page对象:在某个jsp页面中有效
        HttpServletRequest   request对象   在一次请求中有效 (举例:请求转发)  :使用居多
        HttpSession          session对象   (会话管理)里面一种技术          其次,使用居多
        ServletContext       context对象 :全局对象 :代表整个web应用程序

解释:两个方法 一个是存储数据,一个是获取数据,可以在整个项目中使用(不同的Servlet可以使用)

创建两个servlet举例

第一个Servlet代码:

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);
    }
}

第二个Servlet代码:

//从全局对象中获取绑定的内容
public class ContextServletDemo5 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取全局对象
        ServletContext servletContext = this.getServletContext();
        //public Object getAttribute(String name):从全局对象(域对象)获取绑定的内容
        List<String> list = (List<String>) servletContext.getAttribute("list") ;
        if(list!=null){
            for(String s:list){
                System.out.println(s) ;
            }
        }
        System.out.println("-------------获取字符串数据-------------") ;
        String name = (String) servletContext.getAttribute("name");
        System.out.println(name);
        //响应给浏览器一句话
        //解决响应中文
        response.setContentType("text/html;charset=utf-8") ;
        response.getWriter().write("获取数据成功...");
        System.out.println("获取数据成功....");


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

浏览器访问第一个servlet时输出结果:

​ 存储数据成功…

浏览器访问第一个servlet时输出结果:

张三

高圆圆

文章

-------------获取字符串数据-------------

刘桑 并且响应给浏览器一个 获取数据成功…

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

Http协议的一种规范
HttpServletRequest请求对象
			浏览器发请求---->浏览器---network---->可以看到一种格式
								请求头:请求内容
HttpServlerResponse响应对象
			服务器响应给浏览器----->network---->可以看到一种格式
							响应头:响应内容

3.1 请求对象

/**
 * 浏览器将所有的信息都封装到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);
    }
}

输出结果:

请求方式是:GET
请求的url地址是:http://localhost:8080/Day16_Servlet_jsp/requestDemo01
请求的uri是:/Day16_Servlet_jsp/requestDemo01
http版本是:HTTP/1.1

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);
    }
}

输出结果

用户使用的谷歌浏览器

1

3.2 访问对象

/**
 * 浏览器请求服务器的时候,服务器将所有响应信息封装到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/Day16_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/hello.html");

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

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

        doGet(request,response);
    }
}

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

重定向(Redirect):
客户端浏览器向Web应用服务器端发送一个请求,Web服务器端使用HttpServletResponse的sendRedirect()方法将结果(结果中头信息内HTTP状态码为302,Location响应报头域中保存响应回来的地址)返回客户端浏览器;客户端浏览器收到服务器端结果后解析其头部信息,然后自动按照头部指定地址以GET方式再次向Web应用服务器端发请求,此时地址栏URL发生变化,服务器端接收到新的请求再将结果返回至客户端浏览器,客户端浏览器解释执行返回结果并将执行结果显示给用户,至此该过程结束。

请求转发(Forward):
这里的“请求”是名词,请求转发指客户端浏览器向Web服务器端发送请求,服务器端收到请求后进行相应处理后再将该请求转发到另外的资源(即这一“转发”操作是在Web服务器端执行的),服务器端对该资源进行处理后反馈给客户端。

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

5.快速jsp的快速使用

Jsp的本质就是一个Servlet
  jsp:Java Server Page :写java代码的html页面----->目的 渲染数据--展示数据
 了解:
 	Jsp执行流程		
 			翻译----jsp文件---翻译.java文件
 			编译---->将.java文件---.class文件

6.引入Jsp的el表达式 ${可以从域对象中获取的后台数据}+jsp的核心标签库 (重点)

c:forech
c:if
c:choose
     c:when
     c:otherwise
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值