Servlet第三方架包使用2

Servlet第三方架包使用 1
https://blog.csdn.net/qq_36390044/article/details/79705675

使用Servlet (模板创建模式)

public class Demo01 extends HttpServlet{
    //声明一个ServletConfig对象 当做成员变量
    private ServletConfig config;

    //初始化方法(通过该方法的参数  获取ServletConfig对象)
    //ServletConfig对象保存的是servlet中的配置信息
    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        //接收一下ServletConfig
        this.config = config;
    }
    public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException IOException{
        //获取servlet的配置信息 
        getInitParameter(name); //参数是配置时的name(相当于key)

        //用key获取对应的value
        String value = this.config.getInitParameter("encoding");
    }
    //接收post请求
    public void doPost(HttpServletRequest req ,HttpServletResponse resp)throws ServletException IOException{
        super.doget(req ,resp);
    }


}

设置全局 配置信息

public class Demo01 extends HttpServlet{
    public void init(ServletConfig config)throws ServletException{
        super.init(config);
    }
    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException ,IOException{
        //获取config对象
            ServletConfig config  = this.getServletConfig();
            //取出Servlet的配置信息
        string value = config.getInitParameter("username");
        //打印取出配置的信息
        System.out.prinrln(value);

        //获取 context域对象
        ServletContext application = this.getServletContext();
        //取出context域对象配置信息
        String value = application.getIntitParameter("value");
        //打印context域对象信息
        System.out.println(value);
    }
    public void doPost(HttpServletRequset request , HttpServletResponse resoponse) throws  ServletException , IOExcption{
        doGet(request , response);
    }
}

获取服务器上的真实文件路径 并读取 使用Context域对象获取任意资源路径

public class  Demo02  extends HttpServlet{
        public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException{
             //获取a文件 key = aaaaa 
             ServletContext application =  this.getServletContext();
             //获取服务器上的真实路径(绝对路径 磁盘路径)
           String path = application.getRealpath("/WEB-INF/classes/a.properties")
           //打印从服务器上获取的路径
            System.out.println(path);

            //利用io流  读取文件
            Properties properties = new Properties();
            properties.load(new FileInputStream(path));
            Syetem.out.println(properties.getProperty("key"));

             //获取b文件 key = bbbbb
            ServletContext application = this.getServletContext();
            //获取服务器上的真实路径(绝对路径 磁盘路径)
            String path2 = application.getRealpath("WEB-INF/classes/com/lanou3g/b.properties");
            //打印从服务器上获取的路径
            System.out.println(path2);

            //利用io流 读取文件
            Properties properties2 = new Properties();
            properties2.load(new FileInputStream(path));
            System.out.println(properties2.getProperty("key"));

            //获取c文件 key = ccccc;
            ServletContext application = this.getServletContext();
            //获取服务器上的真实路径(绝对路径 磁盘路径)
            String path3 = application.getRealpath("WEB-INF/c.properties");
            System.out.println(path3)

            //利用 io流读取文件
            Properties  properties3 = new  Properties();
            properties3.load(new FileInputStream(path));
            System.out.println(properties3.getProperty("key"));



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

        }
}

请求转发

//浏览器只发起了一次请求
//servlet内部做的请求转发 浏览器 并不知道

public class Demo03  extends  HttpServlet{
    public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException , IOException{
        System.out.println("你好");
        System.out.println("我不好");

        //获取context域对象
        ServletContext appliction = this.getServletContext();

        //从context域中 获取 请求转发器
        RequestDispatcher dispatcher =  appliction.getRequestDispatcher("/demo04");
        //进行请求转发
        dispatcher.forward(request , response);
        System.out.println("饿了, 刚点了外卖")
    }

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

}

创建一个新的类 与Demo03关联

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


}

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");//name 内容的格式  value是设置内容的编码格式

            //这句代表以上两句的方法
            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 {
//                  System.out.println(response.getClass().getName()); 获取类的名字
                    //获取服务器上的图片路径
                    String path = this.getServletContext().getRealPath("/WEB-INF/classes/团子大家族.png");
                    //字符串切割 获取图片的名字
                    int index = path.lastIndexOf("/");
                    String filebname = path.substring(index+1);
                    //修改文件名字的字符集
                    filebname = new String(filebname.getBytes(), "iso-8859-1");
//                  System.out.println(filebname);
                    //添加响应头 (需要拼接文件的名字)
                    response.setHeader("content-disposition", "attachment;filename=" + filebname);
                    //告诉浏览器文件下载的格式添加响应头
                    response.setHeader("content-type", "image/png");

                    //从服务器中读取图片
                    FileInputStream fis = new FileInputStream(path);
                    //注意:需要获取response当中的 字节流
                    ServletOutputStream sos = response.getOutputStream();
                    //边读编写
                    int len = 0;
                    byte[] bs = new byte[1024];
                    while ((len=fis.read(bs)) != -1) {

                        //响应回浏览器
                        sos.write(bs,0, len);
                        //如果只是单纯的把图片响应回去
                        //浏览器并不知道你要干嘛(下载 或 浏览)
                        //需要通过响应头 通知浏览器  我这个文件给你, 是供下载使用的
                        //content-disposition attachment;filename = content-type image/jpeg

                        //new String(filename.getBytes(), "iso-8859-1")


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

    }

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

}

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

请求重定向 和 请求转发的区别 (重点)

请求重定向 : 请求重定向是发起的两次请求(请求地址发生了变化)

请求转发 : 请求转发只是一次请求

响应时要注意的细节

从response中获取的字符流 和字节流

在同一个servlet不能同时使用.

response 可以添加响应头

public class Demo07 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                    //fun1(response);       
                    //fun2(response);
                    //fun3(response);

    }
    private void fun3(HttpServletResponse response) throws IOException {
        //设置  响应的字符集 
        response.setContentType("text/html;charset = UTF-8");
        //三秒后  完成注册   跳转一个网址
        response.setHeader("refresh", "3;url=/demo08");

        response.getWriter().write("3秒后 跳转 很开心");
    }
    private void fun2(HttpServletResponse response) throws IOException {
        //添加刷新头  (每秒刷新一次)
response.setIntHeader("refresh", 1);
        //添加一个随机数
        response.getWriter().write(Math.random() + "");
    }
            //通过添加请求头的方式  请求重定向
    private void fun1(HttpServletResponse response) {
        System.out.println("我要借钱");
        System.out.println("我没有  去找demo08");
            //添加重定向响应头   配置
        //注意: 添加头信息请求地址的时候  需要写明 工程名
        response.setHeader("location", "/SH-web-servlet02/demo08");
        //添加重定向状态码
        response.setStatus(302);
        System.out.println("我去了");
    }

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

}

uri (全球统一标示符) 可视化分析领域 Tableau
HttpServletResponse 请求对象包含: 请求行 请求头 请求体

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请求) : 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 );

            //判断请求过来的浏览器    
            //System.out.println(request); org.apache.catalina.connector.RequestFacade@71bbe9e8
            //可以通过请求头中的信息获取用户使用浏览器
            String header = request.getHeader("User-Agent");
            //Firefox chrome       
            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);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36390044/article/details/79720942