Java之Servlet核心知识详解

设置全局配置信息

    public class Demo01 extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 获取Context域对象
            ServletContext application = this.getServletContext();
            // 获取全局配置信息
            String value = application.getInitParameter("key");
            System.out.println(value);
        }

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

    }

web.xml文件配置

  <!-- 设置全局配置信息 -->
  <context-param>
    <param-name>key</param-name>
    <param-value>value</param-value>
  </context-param>
  <servlet>
    <servlet-name>demo01</servlet-name>
    <servlet-class>com.lanou3g.Demo01</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>demo01</servlet-name>
    <url-pattern>/demo01</url-pattern>
  </servlet-mapping>

获取服务器上的真实文件路径(并读取)

使用Context域对象获取 可以获取到服务器上的任意资源路径

    public class Demo02 extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 获取a文件
            ServletContext application1 = this.getServletContext();
            // 获取服务器上的真实路径  绝对路径/磁盘路径
            String path1 = application1.getRealPath("/WEB-INF/classes/a.properties");
            System.out.println(path1);
            // 读取文件
            Properties properties1 = new Properties();
            properties1.load(new FileInputStream(path1));
            String value1 = properties1.getProperty("key");
            System.out.println(value1);

            // 读取b文件
            ServletContext application2 = this.getServletContext();
            String path2 = application2.getRealPath("/WEB-INF/classes/com/lanou3g/b.properties");
            System.out.println(path2);
            Properties properties2 = new Properties();
            properties2.load(new FileInputStream(path2));
            String value = properties2.getProperty("key");
            System.out.println(value);

            // 读取c文件
            ServletContext application3 = this.getServletContext();
            String path3 = application3.getRealPath("/WEB-INF/c.properties");
            System.out.println(path3);
            Properties properties3 = new Properties();
            properties3.load(new FileInputStream(path3));
            String value3 = properties3.getProperty("key");
            System.out.println(value3);
        }

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

    }

请求转发

Servlet内部做的请求转发 浏览器并不知道
注意:浏览器只是发起一次请求

    public class Demo03 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("我要借钱");
            System.out.println("我没钱 找demo04借");
            // 获取Context域对象
            ServletContext application = this.getServletContext();
            // 从Context域中 获取请求转发器
            RequestDispatcher dispatcher = application.getRequestDispatcher("/demo04");
            // 进行请求转发
            dispatcher.forward(request, response);
            System.out.println("我搞定了");
        }

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

    }

    public class Demo04 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("我有钱");
        }

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

打印顺序:我要借钱 –> 我没钱 找demo04借 –> 我有钱 –> 我搞定了
请求转发

HttpServletResponse(服务器的响应对象)

响应对象都有什么?
    响应行:http/1.1 状态码200
    响应头:告诉浏览器我要做什么 例如响应给你的文件需要下载 以什么编码格式查看网页 解析数据
    响应体:响应回浏览器的数据
    public class Demo05 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            /*
             * Tomcat默认编码格式 iso-8859-1
             * 设置服务器的编码格式 response.setCharacterEncoding("UTF-8");
             * 告诉浏览器要使用什么编码格式来查看
             * 添加响应头 response.setHeader("content-type", "text/html;charset=UTF-8");
             */ 
            // 这句代表以上两句的方法
            response.setContentType("text/html;charset=UTF-8");

            /*
             * 给浏览器响应
             * 从响应对象中HttpServletResponse获取
             * 这个流对象不是你自己创建的 要从响应中获取
             */
            PrintWriter out = response.getWriter();
            out.write("哈哈哈");
        }

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

    }

下载文件

用户发送请求,请求到访问的Servlet
Servlet处理请求(把服务器上的图片以流的形式使用response响应给用户浏览器)
实现代码如下

public class Demo06 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取服务器上的图片路径
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/团子大家族.png");

        // 字符串切割 获取图片的名字
        String[] split = path.split("/");
        String filename = split[split.length-1];

        // 修改文件名字的字符集
        filename = new String(filename.getBytes(), "iso-8859-1");

        // 添加响应头(需要拼接文件的名字)
        // 通知浏览器这个文件是下载用的
        response.setHeader("content-disposition", "attachment;filename=" + filename);

        // 添加响应头 告诉浏览器文件下载的格式
        response.setHeader("content-type", "image/png");

        // 从服务器中读取图片
        FileInputStream fis = new FileInputStream(path);

        // 注意:需要获取response当中的字节流
        ServletOutputStream sos = response.getOutputStream();

        // 边读边写
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            /*
             * 响应回浏览器
             * 如果只是单纯的把图片响应回去
             * 浏览器并不知道你要下载或浏览
             * 需要通过响应头 通知浏览器 这个文件是下载用的
             */
            sos.write(b, 0, len);
        }

        // 自己创建的流自己关
        fis.close();
    }

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

}

请求重定向

浏览器发起请求(请求Servlet)
Servlet给浏览器一个响应
在响应中会携带一个重定向响应头(头中有重定向的访问地址)
浏览器接到这个响应后 发现重定向响应头
再一次发起请求 去访问重定向响应头中的地址

请求重定向和请求转发的区别
    请求重定向是发起两次请求(请求地址发生了变化)
    请求转发只是一次请求

响应时要注意细节
从response中获取的字符流和字节流 在同一个servlet中不能同时使用

通过添加请求头的方式请求重定向

public class Demo07 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("借钱");
        System.out.println("我没有 找demo08");
        // 添加重定向响应头(注意:添加头信息请求地址的时候 需要写明工程名)
        response.setHeader("location", "/sh-web-servlet02/demo08");
        // 添加重定向状态码
        response.setStatus(302);
        System.out.println("我去了");

        //fun1(response);
        //fun2(response);
    }

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

}

public class Demo08 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("借了");
    }

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

}

执行顺序:借钱 –> 我没有 找demo08 –> 我去了 –> 借了
请求重定向
添加刷新头

    private void fun1(HttpServletResponse response) throws IOException {
        // 添加刷新头 (每秒刷新一次)
        response.setIntHeader("refresh", 1);
        // 添加随机数
        response.getWriter().write(Math.random() + "");
    }

    private void fun2(HttpServletResponse response) throws IOException {
        // 设置响应的字符集
        response.setContentType("text/html;charset=utf-8");
        // 3秒后 跳转一个请求地址
        response.setHeader("refresh", "3;url=/sh-web-servlet02/demo08");
        response.getWriter().write("三秒后跳转");
    }

HttpServletRequest(请求对象)

请求对象包含:请求行、请求头、请求体

public class Demo08 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 打印获取请求的网址 http://localhost:8080/sh-web-servlet02/demo08
        System.out.println(request.getRequestURL());
        // /sh-web-servlet02/demo08
        System.out.println(request.getRequestURI());
        // 获取请求的类型 用浏览器直接请求的都是get请求
        System.out.println(request.getMethod());
        // 获取请求的路径(相对路径) /sh-web-servlet02
        System.out.println(request.getContextPath());

        // 获取请求中携带的参数
        // 参数是 你提交表单时 表单的name属性
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + " " + password);

        // 判断浏览器
        // 可以通过请求中的信息 获取用户使用的浏览器
        String header = request.getHeader("User-Agent");
        System.out.println(header);
        if (header.toLowerCase().contains("firefox")) {
            System.out.println("用的是火狐");
        } else if(header.toLowerCase().contains("chrome")){
            System.out.println("用的是谷歌");
        } else {
            System.out.println("其他");
        }
    }

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

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值